-
Notifications
You must be signed in to change notification settings - Fork 34
/
jwt.go
86 lines (75 loc) · 1.79 KB
/
jwt.go
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
package jwt
import (
"time"
"github.com/golang-jwt/jwt/v4"
"github.com/machinefi/w3bstream/pkg/depends/base/types"
)
type Jwt struct {
Issuer string `env:""`
ExpIn types.Duration `env:""`
SignKey string `env:""`
// Method SigningMethod `env:""`
}
func (c *Jwt) SetDefault() {}
func (c *Jwt) Init() {
if c.ExpIn == 0 {
c.ExpIn = types.Duration(time.Hour)
}
if c.SignKey == "" {
c.SignKey = "xxxx" // stringsx.GenRandomVisibleString(16)
}
}
func (c *Jwt) GenerateTokenByPayload(payload interface{}) (string, error) {
claim := &Claims{
Payload: payload,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: c.getNumericDate(),
Issuer: c.Issuer,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
return token.SignedString([]byte(c.SignKey))
}
func (c *Jwt) GenerateTokenWithoutExpByPayload(payload interface{}) (string, error) {
claim := &Claims{
Payload: payload,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: nil,
Issuer: c.Issuer,
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claim)
return token.SignedString([]byte(c.SignKey))
}
func (c *Jwt) ParseToken(v string) (*Claims, error) {
t, err := jwt.ParseWithClaims(
v,
&Claims{},
func(token *jwt.Token) (interface{}, error) {
return []byte(c.SignKey), nil
},
)
if err != nil {
return nil, InvalidToken.StatusErr().WithDesc(err.Error())
}
if t == nil {
return nil, InvalidToken
}
claim, ok := t.Claims.(*Claims)
if !ok || !t.Valid {
return nil, InvalidClaim
}
return claim, nil
}
func (c *Jwt) getNumericDate() (numericDate *jwt.NumericDate) {
if c.ExpIn == 0 {
numericDate = nil
} else {
numericDate = &jwt.NumericDate{Time: time.Now().Add(c.ExpIn.Duration())}
}
return
}
type Claims struct {
Payload interface{}
jwt.RegisteredClaims
}