user_token.go
1.2 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
package domain
import (
"errors"
jwt "github.com/dgrijalva/jwt-go"
"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/constant"
"time"
)
type UserToken struct {
UserId int64 `json:"userId"`
CompanyId int64 `json:"companyId"`
CompanyType int `json:"companyType"`
jwt.StandardClaims
}
func (tk UserToken) GenerateToken() (string, error) {
tk.StandardClaims = jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Duration(constant.JWTExpiresIn) * time.Second).Unix(),
Issuer: "digital-platform",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, tk)
return token.SignedString([]byte(constant.JWTSecretKey))
}
func (tk *UserToken) ParseToken(str string) error {
tokenClaims, err := jwt.ParseWithClaims(
str,
tk,
func(token *jwt.Token) (interface{}, error) {
return []byte(constant.JWTSecretKey), nil
})
if err != nil {
return err
}
if claim, ok := tokenClaims.Claims.(*UserToken); ok && tokenClaims.Valid {
*tk = *claim
return nil
}
return errors.New("token 解析失败")
}
// CheckUserInfo 如果UserToken有效 返回:true 否则返回false
func (tk *UserToken) CheckUserInfo() bool {
return !(tk.UserId > 100000000 || tk.UserId <= 0)
}