-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
81 lines (71 loc) · 1.61 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
package jwt
import (
"errors"
"github.com/golang-jwt/jwt/v4"
"time"
)
const (
defaultKey = "12345678"
fifteenDayHours = 15 * 24
)
type Config struct {
Key string
ExpireTime time.Duration
Issuer string
}
type CustomClaims struct {
ID interface{} // token unique id
LoginAt int64 // login timestamp
jwt.RegisteredClaims
}
type Service struct {
C *Config
}
// New a token srv
func New(c *Config) *Service {
if c == nil {
c = &Config{
Key: defaultKey,
ExpireTime: time.Hour * fifteenDayHours,
}
}
s := &Service{
C: c,
}
if c.ExpireTime == 0 {
s.C.ExpireTime = time.Hour * fifteenDayHours
}
return s
}
// DecodeToken a token string into a token object
func (s *Service) DecodeToken(tokenString string) (*CustomClaims, error) {
// Parse the token
token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(s.C.Key), nil
})
if err != nil {
return nil, errors.New("")
}
// Validate the token and return the custom claims
if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
return claims, nil
} else {
return nil, err
}
}
// EncodeToken a claim into a JWT
func (s *Service) EncodeToken(Id interface{}, loginAt time.Time) (string, error) {
// Create the Claims
claims := CustomClaims{
Id,
loginAt.Unix(),
jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(s.C.ExpireTime)),
Issuer: s.C.Issuer,
},
}
// Create token
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign token and return
return token.SignedString([]byte(s.C.Key))
}