user_auth.go
1.9 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
package domain
import (
"errors"
"time"
"github.com/dgrijalva/jwt-go"
)
type UserAuth struct {
jwt.StandardClaims
UserId int64 `json:"userId"`
CompanyId int64 `json:"companyId"`
CompanyName string `json:"companyName"`
Phone string `json:"phone"`
PlatformId int `json:"platformId"`
Name string `json:"name"`
AdminType int `json:"adminType"`
}
var issuer = "performance"
var secretKey = "Ma9HXITeliSYS43Z"
var JWTExpiresSecond = 3600 * 24
// CreateAccessToken 生成token
func (userAuth *UserAuth) CreateAccessToken() (string, error) {
userAuth.StandardClaims = jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Duration(JWTExpiresSecond) * time.Second).Unix(),
Issuer: issuer,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, userAuth)
return token.SignedString([]byte(secretKey))
}
// ParseAccessToken 解析token
func (userAuth *UserAuth) ParseAccessToken(token string) (*UserAuth, error) {
user := &UserAuth{}
tokenClaims, err := jwt.ParseWithClaims(token, user, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil || tokenClaims == nil {
return nil, errors.New("解析token失败")
}
if claim, ok := tokenClaims.Claims.(*UserAuth); ok && tokenClaims.Valid {
user.UserId = claim.UserId
user.CompanyId = claim.CompanyId
user.Phone = claim.Phone
user.PlatformId = claim.PlatformId
user.Name = claim.Name
user.AdminType = claim.AdminType
user.CompanyName = claim.CompanyName
return user, nil
}
return user, errors.New("解析token失败")
}
func (userAuth *UserAuth) CreateRefreshToken() (string, error) {
expiresAt := time.Now().Add(time.Duration(JWTExpiresSecond*2) * time.Second).Unix()
userAuth.StandardClaims = jwt.StandardClaims{
ExpiresAt: expiresAt,
Issuer: issuer,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, userAuth)
return token.SignedString([]byte(secretKey))
}