forked from tiagorlampert/CHAOS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
64 lines (57 loc) · 1.49 KB
/
jwt.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
59
60
61
62
63
64
package middleware
import (
"bytes"
"github.com/appleboy/gin-jwt/v2"
"github.com/gin-gonic/gin"
jwtUtil "github.com/tiagorlampert/CHAOS/internal/utils/jwt"
"github.com/tiagorlampert/CHAOS/services/auth"
"github.com/tiagorlampert/CHAOS/services/user"
"net/http"
"time"
)
const (
nameToDisplay = "chaos"
tokenLookup = "cookie:jwt"
tokenHeaderName = "Bearer"
authorizedKey = "authorized"
)
type JWT struct {
*jwt.GinJWTMiddleware
}
func NewJwtMiddleware(
authService auth.Service,
userService user.Service,
) *JWT {
secret, err := authService.GetSecret()
if err != nil {
panic(err)
}
authHandler := newAuthHandler(userService)
m, err := jwt.New(&jwt.GinJWTMiddleware{
Realm: nameToDisplay,
Key: bytes.NewBufferString(secret).Bytes(),
Timeout: time.Hour,
MaxRefresh: time.Hour,
IdentityKey: jwtUtil.IdentityKey,
TokenLookup: tokenLookup,
TokenHeadName: tokenHeaderName,
SendCookie: true,
TimeFunc: time.Now,
PayloadFunc: authHandler.payloadFuncHandler,
IdentityHandler: authHandler.identityHandler,
Authenticator: authHandler.authenticatorHandler,
Unauthorized: authHandler.unauthorizedHandler,
LogoutResponse: authHandler.logoutResponseHandler,
})
if err != nil {
panic(err)
}
return &JWT{m}
}
func (j *JWT) AuthAdmin(c *gin.Context) {
claims := jwt.ExtractClaims(c)
if claims[jwtUtil.IdentityKey] != jwtUtil.IdentityAdminUser {
c.AbortWithStatus(http.StatusForbidden)
return
}
}