forked from tiagorlampert/CHAOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathauth_handler.go
58 lines (50 loc) · 1.49 KB
/
auth_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package middleware
import (
jwt "github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
"github.com/tiagorlampert/CHAOS/entities"
jwtUtil "github.com/tiagorlampert/CHAOS/internal/utils/jwt"
"github.com/tiagorlampert/CHAOS/services/user"
"net/http"
)
type authHandler struct {
UserService user.Service
}
func newAuthHandler(userService user.Service) *authHandler {
return &authHandler{UserService: userService}
}
func (a authHandler) payloadFuncHandler(data interface{}) jwt.MapClaims {
if v, ok := data.(*entities.User); ok {
return jwt.MapClaims{
authorizedKey: true,
jwtUtil.IdentityKey: v.Username,
}
}
return jwt.MapClaims{}
}
func (a authHandler) identityHandler(c *gin.Context) interface{} {
claims := jwt.ExtractClaims(c)
return &entities.User{
Username: claims[jwtUtil.IdentityKey].(string),
}
}
func (a authHandler) authenticatorHandler(c *gin.Context) (interface{}, error) {
var user entities.User
if err := c.ShouldBind(&user); err != nil {
return "", jwt.ErrMissingLoginValues
}
if a.UserService.Login(user.Username, user.Password) {
return &entities.User{
Username: user.Username,
}, nil
}
return nil, jwt.ErrFailedAuthentication
}
func (a authHandler) unauthorizedHandler(c *gin.Context, code int, message string) {
c.HTML(http.StatusUnauthorized, "login.html", gin.H{"unauthorized": true})
return
}
func (a authHandler) logoutResponseHandler(c *gin.Context, code int) {
c.HTML(http.StatusOK, "login.html", gin.H{"unauthorized": true})
return
}