jwt.go
1.4 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
package tool
import (
jwt "github.com/golang-jwt/jwt/v4"
"gitlab.fjmaimaimai.com/allied-creation/sumifcc-bchart/pkg/config"
"time"
)
type UserToken struct {
UserId int64 `json:"userId"`
CoachId int64 `json:"coach_id"`
AdminId int64 `json:"adminId"`
ClientType string `json:"clientType"`
AccessShops []int64 `json:"accessShops"`
}
func (tk UserToken) GenerateToken(jwtConfig config.JwtAuth) (string, error) {
claims := make(jwt.MapClaims)
claims["exp"] = time.Now().Unix() + jwtConfig.Expire
claims["iat"] = time.Now().Unix()
claims["UserId"] = tk.UserId
claims["CoachId"] = tk.CoachId
claims["AdminId"] = tk.AdminId
claims["ClientType"] = tk.ClientType
claims["AccessShops"] = tk.AccessShops
token := jwt.New(jwt.SigningMethodHS256)
token.Claims = claims
return token.SignedString([]byte(jwtConfig.AccessSecret))
}
func (tk *UserToken) ParseToken(jwtConfig config.JWT, str string) error {
//tokenClaims, err := jwt.ParseWithClaims(
// str,
// tk,
// func(token *jwt.Token) (interface{}, error) {
// return []byte(jwtConfig.Secret), nil
// })
//if err != nil {
// return err
//}
//if claim, ok := tokenClaims.Claims.(*UserToken); ok && tokenClaims.Valid {
// *tk = *claim
// return nil
//}
//return errors.New("token 解析失败")
return nil
}
// CheckUserInfo 如果UserToken有效 返回:true 否则返回false
func (tk *UserToken) CheckUserInfo() bool {
return !(tk.UserId > 100000000 || tk.UserId <= 0)
}