瀏覽代碼

safe assert

Paul 6 年之前
父節點
當前提交
dc9695a41e
共有 2 個文件被更改,包括 25 次插入17 次删除
  1. 13
    9
      middleware/auth/auth.go
  2. 12
    8
      middleware/auth/optional_auth.go

+ 13
- 9
middleware/auth/auth.go 查看文件

@@ -51,16 +51,20 @@ func Auth(authKey string) gin.HandlerFunc {
51 51
 			return
52 52
 		}
53 53
 
54
-		mapClaims := token.Claims.(jwt.MapClaims)
55
-		expired := int64(mapClaims[ctxRequestTokenExpired].(float64))
56
-		if expired < time.Now().Unix() {
57
-			// Only cookie is blank value, check token expired
58
-			if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
59
-				ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
60
-				return
54
+		if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
55
+			if expired, ok := mapClaims[ctxRequestTokenExpired].(float64); ok {
56
+				if int64(expired) < time.Now().Unix() {
57
+					// Only cookie is blank value, check token expired
58
+					if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
59
+						ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
60
+						return
61
+					}
62
+				}
61 63
 			}
62
-		}
63 64
 
64
-		ctx.Set(CtxRequestHeaderUserId, int(mapClaims[CtxRequestHeaderUserId].(float64)))
65
+			if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
66
+				ctx.Set(CtxRequestHeaderUserId, int(uid))
67
+			}
68
+		}
65 69
 	}
66 70
 }

+ 12
- 8
middleware/auth/optional_auth.go 查看文件

@@ -40,15 +40,19 @@ func OptionalAuth(authKey string) gin.HandlerFunc {
40 40
 			return
41 41
 		}
42 42
 
43
-		mapClaims := token.Claims.(jwt.MapClaims)
44
-		expired := int64(mapClaims[ctxRequestTokenExpired].(float64))
45
-		if expired < time.Now().Unix() {
46
-			// Only cookie is blank value, check token expired
47
-			if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
48
-				return
43
+		if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
44
+			if expired, ok := mapClaims[ctxRequestTokenExpired].(float64); ok {
45
+				if int64(expired) < time.Now().Unix() {
46
+					// Only cookie is blank value, check token expired
47
+					if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
48
+						return
49
+					}
50
+				}
49 51
 			}
50
-		}
51 52
 
52
-		ctx.Set(CtxRequestHeaderUserId, int(mapClaims[CtxRequestHeaderUserId].(float64)))
53
+			if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
54
+				ctx.Set(CtxRequestHeaderUserId, int(uid))
55
+			}
56
+		}
53 57
 	}
54 58
 }