Browse Source

expire for more condition

Paul 6 years ago
parent
commit
f4478e348d
1 changed files with 24 additions and 9 deletions
  1. 24
    9
      middleware/auth/auth.go

+ 24
- 9
middleware/auth/auth.go View File

2
 
2
 
3
 import (
3
 import (
4
 	"fmt"
4
 	"fmt"
5
-	"net/http"
6
-	"time"
7
-
8
 	"github.com/dgrijalva/jwt-go"
5
 	"github.com/dgrijalva/jwt-go"
9
 	"github.com/gin-gonic/gin"
6
 	"github.com/gin-gonic/gin"
7
+	"net/http"
8
+	"time"
10
 )
9
 )
11
 
10
 
12
 const (
11
 const (
53
 
52
 
54
 		if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
53
 		if mapClaims, ok := token.Claims.(jwt.MapClaims); ok {
55
 			if expired, ok := mapClaims[ctxRequestTokenExpired].(float64); ok {
54
 			if expired, ok := mapClaims[ctxRequestTokenExpired].(float64); ok {
56
-				if expired == 0 {
55
+				switch true {
56
+				case expired > 0:
57
+					if int64(expired) < time.Now().Unix() {
58
+						ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
59
+						return
60
+					}
61
+
62
+					// todo check expired from server
63
+				case expired == 0:
57
 					// Only cookie is exists, check token expired. app expired by itself call logout when app exit
64
 					// Only cookie is exists, check token expired. app expired by itself call logout when app exit
58
 					if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
65
 					if _, err := ctx.Cookie(ctxRequestCookieAuthorization); err != nil {
59
 						ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
66
 						ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
60
 						return
67
 						return
61
 					}
68
 					}
62
-				}
63
 
69
 
64
-				if expired < 0 || (int64(expired) < time.Now().Unix()) {
70
+				default:
65
 					ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
71
 					ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token timeout"})
66
 					return
72
 					return
67
 				}
73
 				}
68
-			}
69
 
74
 
70
-			if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
71
-				ctx.Set(CtxRequestHeaderUserId, int64(uid))
75
+				if uid, ok := mapClaims[CtxRequestHeaderUserId].(float64); ok {
76
+					ctx.Set(CtxRequestHeaderUserId, int64(uid))
77
+				} else {
78
+					ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[CtxRequestHeaderUserId].(float64) error"})
79
+					return
80
+				}
81
+			} else {
82
+				ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, mapClaims[ctxRequestTokenExpired].(float64) error"})
83
+				return
72
 			}
84
 			}
85
+		} else {
86
+			ctx.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"msg": "auth failed, token.Claims.(jwt.MapClaims) error"})
87
+			return
73
 		}
88
 		}
74
 	}
89
 	}
75
 }
90
 }