This repository has been archived by the owner on Nov 29, 2020. It is now read-only.
/
jwt.go
116 lines (101 loc) · 2.76 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
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
package middleware
import (
"time"
"github.com/mohuishou/scuplus-go/config"
"strings"
"github.com/dgrijalva/jwt-go"
jwtmiddleware "github.com/iris-contrib/middleware/jwt"
"github.com/kataras/iris"
"github.com/mohuishou/scuplus-go/cache/api"
)
func jwtMiddle(ctx iris.Context) {
// 登录页面无需验证
if skipJWT(ctx.Path()) {
ctx.Next()
return
}
// token 验证
jwtHandler := jwtmiddleware.New(jwtmiddleware.Config{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(config.Get().JwtSecret), nil
},
// When set, the middleware verifies that tokens are signed with the specific signing algorithm
// If the signing method is not constant the ValidationKeyGetter callback can be used to implement additional checks
// Important to avoid security issues described here: https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/
SigningMethod: jwt.SigningMethodHS256,
})
// jwt 验证
if err := jwtHandler.CheckJWT(ctx); err != nil {
ctx.StopExecution()
return
}
// token信息验证
token := ctx.Values().Get("jwt").(*jwt.Token)
userID, ok := token.Claims.(jwt.MapClaims)["user_id"]
if !ok {
ctx.JSON(map[string]interface{}{
"status": 401,
"msg": "用户尚未登录,获取用户信息失败",
})
ctx.StopExecution()
return
}
// token 时效验证
// end, ok := token.Claims.(jwt.MapClaims)["end"].(float64)
// if !ok || time.Now().Unix() > int64(end) {
// log.Println("[Error]: 登录信息已失效", end)
// ctx.JSON(map[string]interface{}{
// "status": 401,
// "msg": "用户尚未登录,获取用户信息失败",
// })
// ctx.StopExecution()
// return
// }
// 设置用户id
ctx.Values().Set("user_id", userID)
uid := uint(userID.(float64))
if api.Get(uid) > 300 {
ctx.JSON(map[string]interface{}{
"status": 403,
"msg": "访问过于频繁,休息一会儿吧",
})
ctx.StopExecution()
return
}
api.Add(uid)
ctx.Next()
}
// 跳过jwt的链接
func skipJWT(path string) bool {
urls := []string{
"/login",
"/notices",
"/webhook",
"/helps",
}
for _, v := range urls {
if v == path || strings.Contains(path, "debug") {
return true
}
}
return false
}
// GetUserID 获取用户的id
func GetUserID(ctx iris.Context) uint {
uid := ctx.Values().Get("user_id")
switch uid.(type) {
case float64:
return uint(uid.(float64))
}
return 0
}
// CreateToken 新建一个Token
func CreateToken(userID uint) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"user_id": userID,
"end": time.Now().Unix() + 3600*24*15,
"start": time.Now().Unix(),
})
// Sign and get the complete encoded token as a string using the secret
return token.SignedString([]byte(config.Get().JwtSecret))
}