Blame view

Lib/JWT/jwt.go 1.59 KB
8a882f01   aarongao   1.0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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

8a882f01   aarongao   1.0
16
17
18
	auth, _ := json.Marshal(user.Auth)
	claim := jwt.MapClaims{
		"id":       user.Id,
f56bf95d   aarongao   ..
19
		"username": user.Username,
8a882f01   aarongao   1.0
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
		"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
f56bf95d   aarongao   ..
63
	user.Username = claim["username"].(string)
8a882f01   aarongao   1.0
64
65
66
67
	user.UserType = claim["userType"].(string)
	user.ScenicId = claim["scenicId"].(string)

	var jsons []string
f56bf95d   aarongao   ..
68
	json.Unmarshal([]byte(claim["auth"].(string)), &jsons)
8a882f01   aarongao   1.0
69
70
71
	user.Auth = jsons
	return
}