login_token.go
2.3 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package domain
import (
"time"
jwt "github.com/dgrijalva/jwt-go"
)
const (
loginTokenSecret string = "bbe35ad433dd8e67"
accessTokenExpiresAt int64 = 60 * 60 * 2 //两个小时过期
refreshTokenExpiresAt int64 = 3600 * 24 * 30 * 1 //刷新token 一个月过期
authCodeExpire int64 = 60 * 15 //15分钟过期
)
type LoginToken struct {
jwt.StandardClaims
UserId int64 `json:"userId"`
UserBaseId int64 `json:"userBaseId"`
// 账号
Account string `json:"account"`
// 对应平台
Platform string `json:"platform"`
// 公司id
CompanyId int64 `json:"companyId"`
// 组织id
OrgId int64 `json:"orgId"`
// 用户关联的组织列表
Orgs []int64 `json:"orgs"`
// 会话模式 1: 短时效模式 2: 长时效模式(默认)
SessionMode int `json:"sessionMode"`
}
func (t *LoginToken) GenerateAccessToken() (string, error) {
nowTime := time.Now().Unix()
t.StandardClaims = jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: nowTime + accessTokenExpiresAt,
Issuer: "allied_creation_gateway",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, *t)
return token.SignedString([]byte(loginTokenSecret))
}
func (t *LoginToken) GenerateRefreshToken() (string, error) {
nowTime := time.Now().Unix()
expire := refreshTokenExpiresAt
if t.SessionMode == 1 {
expire = accessTokenExpiresAt
}
t.StandardClaims = jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: nowTime + expire,
Issuer: "allied_creation_gateway",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, *t)
return token.SignedString([]byte(loginTokenSecret))
}
func (t *LoginToken) GenerateAuthCode() (string, error) {
nowTime := time.Now().Unix()
t.StandardClaims = jwt.StandardClaims{
NotBefore: nowTime,
IssuedAt: nowTime,
ExpiresAt: nowTime + authCodeExpire,
Issuer: "allied_creation_gateway",
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, *t)
return token.SignedString([]byte(loginTokenSecret))
}
func (t *LoginToken) ParseToken(str string) error {
tokenClaims, err := jwt.ParseWithClaims(
str,
t,
func(token *jwt.Token) (interface{}, error) {
return []byte(loginTokenSecret), nil
})
if err != nil {
return err
}
if claim, ok := tokenClaims.Claims.(*LoginToken); ok && tokenClaims.Valid {
*t = *claim
}
return nil
}