-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
105 lines (89 loc) · 2.01 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package do
import (
"errors"
"fmt"
"math/rand"
"strconv"
"strings"
"time"
"github.com/golang-jwt/jwt/v5"
)
var (
ErrBadIssuer = errors.New("Token Bad Issuer")
ErrExpired = errors.New("Token Expired")
ErrNotValid = errors.New("Token Not Valid")
)
type Token[T any] struct {
secret []byte
exp time.Duration
issuer string
}
func New[T any](
secret []byte,
exp time.Duration,
issuer string,
) *Token[T] {
return &Token[T]{
exp: exp,
issuer: issuer,
secret: secret,
}
}
type Claims[T any] struct {
User T
Nonce string
jwt.RegisteredClaims
}
// Sign `user` can be a id or an object
func (t *Token[T]) Sign(user T) (string, error) {
claims := Claims[T]{
User: user,
Nonce: strconv.FormatInt(rand.Int63(), 10),
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(t.exp)),
Issuer: t.issuer,
},
}
// Create a new token object, specifying signing method and the claims
// you would like it to contain.
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
// Sign and get the complete encoded token as a string using the secret
tokenString, err := token.SignedString(t.secret)
if err != nil {
return "", fmt.Errorf("sign failed: %v", err)
}
return tokenString, nil
}
func (t *Token[T]) Verify(tokenString string) (user T, err error) {
if strings.TrimSpace(tokenString) == "" {
return
}
claims := Claims[T]{}
token, err := jwt.ParseWithClaims(tokenString, &claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return t.secret, nil
})
if err != nil {
err = fmt.Errorf("parse token failed: %v", err)
return
}
if !token.Valid {
err = ErrNotValid
return
}
userInfo := claims.User
exp := claims.ExpiresAt
iss := claims.Issuer
if iss != t.issuer {
err = ErrBadIssuer
return
}
if exp.Unix() <= time.Now().Unix() {
err = ErrExpired
return
}
user = userInfo
return user, nil
}