-
Notifications
You must be signed in to change notification settings - Fork 1
/
jwt.go
83 lines (66 loc) · 1.97 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
package auth
import (
"errors"
"fmt"
"time"
"github.com/ScoreTrak/ScoreTrak/pkg/user"
"github.com/golang-jwt/jwt/v4"
)
type Manager struct {
secretKey string
tokenDuration time.Duration
}
type claim string
const KeyClaim claim = "claim"
// UserClaims represents contents of JWT token.
type UserClaims struct {
jwt.RegisteredClaims
Username string `json:"username"`
TeamID string `json:"team_id"`
Role string `json:"role"`
}
func NewJWTManager(secretKey string, tokenDuration time.Duration) *Manager {
return &Manager{secretKey, tokenDuration}
}
type Config struct {
Secret string `default:"changeme"`
TimeoutInSeconds uint64 `default:"86400"`
}
// Generate creates user claim based on passed user parameter, and encodes it to JWT token.
func (manager *Manager) Generate(user *user.User) (string, error) {
claims := UserClaims{
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(manager.tokenDuration)),
ID: user.ID.String(),
},
Username: user.Username,
Role: user.Role,
TeamID: user.TeamID.String(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(manager.secretKey))
}
var ErrUnexpectedSigningToken = errors.New("unexpected token signing method")
// Verify ensures that the token provided by the client is valid, after which it extracts the claims and returns them.
func (manager *Manager) Verify(accessToken string) (*UserClaims, error) {
token, err := jwt.ParseWithClaims(
accessToken,
&UserClaims{},
func(token *jwt.Token) (interface{}, error) {
_, ok := token.Method.(*jwt.SigningMethodHMAC)
if !ok {
return nil, ErrUnexpectedSigningToken
}
return []byte(manager.secretKey), nil
},
)
if err != nil {
return nil, fmt.Errorf("invalid token: %w", err)
}
claims, ok := token.Claims.(*UserClaims)
if !ok {
return nil, ErrInvalidToken
}
return claims, nil
}
var ErrInvalidToken = errors.New("invalid token claims")