jwt.go
2.3 KB
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
package utils
import (
"github.com/dgrijalva/jwt-go"
"time"
)
type UserTokenClaims struct {
UserId int64 `json:"userId"`
CompanyId int64 `json:"companyId"`
AdminType int `json:"adminType"` //用户类型 1:合伙人 2:高管
Phone string `json:"phone"`
jwt.StandardClaims
}
var jwtSecret = []byte("123456")
//解析 UserTokenClaims
func ParseJWTToken(token string) (*UserTokenClaims, error) {
tokenClaims, err := jwt.ParseWithClaims(token, &UserTokenClaims{}, func(token *jwt.Token) (interface{}, error) {
return jwtSecret, nil
})
if err != nil {
return nil, err
}
if tokenClaims != nil {
if claim, ok := tokenClaims.Claims.(*UserTokenClaims); ok && tokenClaims.Valid {
// TODO:版本兼容
//if claim.CompanyId==0{
// claim.CompanyId = 1
// claim.AdminType = 1
//}
return claim, nil
}
}
return nil, err
}
//生成token
//@uid 用户变化
//@password 密码
//@expire 过期时长
func GenerateToken(uid int64, phone string, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: uid,
Phone: phone,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
func GenerateTokenWithAdminType(uid int64, phone string, adminType int, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: uid,
Phone: phone,
AdminType: adminType,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}
func GenerateTokenWithClaim(claim UserTokenClaims, expire time.Duration) (string, error) {
now := time.Now()
expireTime := now.Add(expire)
claims := UserTokenClaims{
UserId: claim.UserId,
Phone: claim.Phone,
CompanyId: claim.CompanyId,
AdminType: claim.AdminType,
StandardClaims: jwt.StandardClaims{
ExpiresAt: expireTime.Unix(),
Issuer: "jwt",
},
}
tokenClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, err := tokenClaims.SignedString(jwtSecret)
return token, err
}