jwt.go
1.59 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
package JWT
import (
"encoding/json"
"errors"
"github.com/dgrijalva/jwt-go"
"go.mongodb.org/mongo-driver/bson/primitive"
"letu/Config"
"letu/DB"
"time"
)
func CreateToken(user *DB.SMember, exp int64) (tokenss string, err error) {
//自定义claim
auth, _ := json.Marshal(user.Auth)
claim := jwt.MapClaims{
"id": user.Id,
//"mobile": user.Mobile,
"userType": user.UserType,
"scenicId": user.ScenicId,
"auth": string(auth),
"nbf": time.Now().Unix(),
"iat": time.Now().Unix(),
"exp": exp,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
tokenss, err = token.SignedString([]byte(Config.Info.TokenSecret))
return
}
func secret() jwt.Keyfunc {
return func(token *jwt.Token) (interface{}, error) {
return []byte(Config.Info.TokenSecret), nil
}
}
func CheckToken(tokenss string) (err error) {
_, err = jwt.Parse(tokenss, secret())
return err
}
func ParseToken(tokenss string) (user *DB.SMember, err error) {
user = &DB.SMember{}
token, err := jwt.Parse(tokenss, secret())
if err != nil {
return
}
claim, ok := token.Claims.(jwt.MapClaims)
if !ok {
err = errors.New("cannot convert claim to mapclaim")
return
}
//验证token,如果token被修改过则为false
if !token.Valid {
err = errors.New("token is invalid")
return
}
id, _ := primitive.ObjectIDFromHex(claim["id"].(string))
user.Id = &id
//user.Mobile = claim["mobile"].(string)
user.UserType = claim["userType"].(string)
user.ScenicId = claim["scenicId"].(string)
var jsons []string
json.Unmarshal([]byte(claim["auth"].(string)),&jsons)
user.Auth = jsons
return
}