-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.go
53 lines (43 loc) · 1.09 KB
/
token.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
package go_token
import (
"github.com/golang-jwt/jwt/v5"
"time"
)
type (
Token interface {
JwtSign(id int, expireDuration time.Duration) (string, error)
JwtParse(tokenString string) (*claims, error)
}
token struct {
Secret string
}
claims struct {
ID int
jwt.RegisteredClaims
}
)
func (t *token) JwtSign(id int, expireDuration time.Duration) (string, error) {
claims := claims{
id,
jwt.RegisteredClaims{
IssuedAt: jwt.NewNumericDate(time.Now()),
ExpiresAt: jwt.NewNumericDate(time.Now().Add(expireDuration)),
NotBefore: jwt.NewNumericDate(time.Now()),
},
}
return jwt.NewWithClaims(jwt.SigningMethodHS256, claims).SignedString([]byte(t.Secret))
}
func (t *token) JwtParse(tokenString string) (*claims, error) {
tokenClaims, err := jwt.ParseWithClaims(tokenString, &claims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(t.Secret), nil
})
if tokenClaims != nil {
if claims, ok := tokenClaims.Claims.(*claims); ok && tokenClaims.Valid {
return claims, nil
}
}
return nil, err
}
func New(secret string) Token {
return &token{Secret: secret}
}