|
@@ -1,9 +1,9 @@
|
1
|
1
|
package auth
|
2
|
2
|
|
3
|
3
|
import (
|
4
|
|
- "fmt"
|
5
|
4
|
"net/http"
|
6
|
5
|
|
|
6
|
+ "fmt"
|
7
|
7
|
"github.com/dgrijalva/jwt-go"
|
8
|
8
|
"github.com/gin-gonic/gin"
|
9
|
9
|
)
|
|
@@ -21,26 +21,23 @@ func OptionalAuth(authKey string) gin.HandlerFunc {
|
21
|
21
|
tokenFromHeader = "Bearer " + tokenFromCookie
|
22
|
22
|
}
|
23
|
23
|
|
24
|
|
- if len(tokenFromHeader) < 8 {
|
25
|
|
- ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed"})
|
26
|
|
- return
|
27
|
|
- }
|
|
24
|
+ if len(tokenFromHeader) > 7 {
|
|
25
|
+ token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
|
|
26
|
+ if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
27
|
+ return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
|
28
|
+ }
|
28
|
29
|
|
29
|
|
- token, err := jwt.Parse(tokenFromHeader[7:], func(token *jwt.Token) (interface{}, error) {
|
30
|
|
- if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
31
|
|
- return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
32
|
|
- }
|
|
30
|
+ return []byte(authKey), nil
|
|
31
|
+ })
|
33
|
32
|
|
34
|
|
- return []byte(authKey), nil
|
35
|
|
- })
|
36
|
|
-
|
37
|
|
- if err != nil || !token.Valid {
|
38
|
|
- return
|
39
|
|
- }
|
|
33
|
+ if err != nil || !token.Valid {
|
|
34
|
+ return
|
|
35
|
+ }
|
40
|
36
|
|
41
|
|
- if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
|
42
|
|
- if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
|
43
|
|
- ctx.Set(CtxRequestHeaderUserId, int64(uid))
|
|
37
|
+ if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
|
|
38
|
+ if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
|
|
39
|
+ ctx.Set(CtxRequestHeaderUserId, int64(uid))
|
|
40
|
+ }
|
44
|
41
|
}
|
45
|
42
|
}
|
46
|
43
|
}
|