-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
145 lines (98 loc) · 2.43 KB
/
main.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
package jwtmiddleware
import (
"errors"
"fmt"
src "github.com/AndreaNicola/strapi-rest-client"
"github.com/dgrijalva/jwt-go"
"github.com/gin-gonic/gin"
"net/http"
"os"
"strings"
"time"
)
var secret []byte
func init() {
jwtAccessSecret := os.Getenv("JWT_ACCESS_SECRET")
if jwtAccessSecret == "" {
panic("JWT_ACCESS_SECRET env variable is not set")
}
secret = []byte(jwtAccessSecret)
}
func tokenValidationAndExtraction(context *gin.Context) error {
jwtTokenString, err := extractToken(context)
if err != nil {
return err
}
jwtToken, err := jwt.Parse(*jwtTokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secret, nil
})
if err != nil {
return err
}
claims, ok := jwtToken.Claims.(jwt.MapClaims)
if !(ok || jwtToken.Valid) {
return errors.New("token is not valid")
}
// is it useless? i don't know...
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return errors.New("token expired")
}
if ok && jwtToken.Valid {
if context.Keys == nil {
context.Keys = make(map[string]interface{})
}
context.Keys["userId"] = claims["id"]
}
return nil
}
func DummyMiddleware() gin.HandlerFunc {
return func(context *gin.Context) {
}
}
func JwtMiddleware() gin.HandlerFunc {
return func(context *gin.Context) {
err := tokenValidationAndExtraction(context)
if err != nil {
context.AbortWithStatusJSON(http.StatusUnauthorized, err.Error())
return
}
context.Next()
}
}
func extractToken(context *gin.Context) (*string, error) {
bearerToken := context.GetHeader("Authorization")
if bearerToken == "" {
return nil, errors.New("no bearer token")
}
strArr := strings.Split(bearerToken, " ")
if len(strArr) != 2 {
return nil, errors.New("no bearer token")
}
return &strArr[1], nil
}
func StrapiCheckRoleMiddleware(src src.StrapiRestClient, roles ...string) func(ctx *gin.Context) {
return func(ctx *gin.Context) {
userId := ctx.Keys["userId"].(float64)
currentUser, err := src.GetUser(int(userId))
if err != nil {
ctx.AbortWithStatusJSON(403, &gin.H{
"error": "forbidden",
})
return
}
hasRole := false
for _, e := range roles {
hasRole = hasRole || e == currentUser.Role.Type
}
if !hasRole {
ctx.AbortWithStatusJSON(403, &gin.H{
"error": "forbidden",
})
return
}
ctx.Next()
}
}