-
Notifications
You must be signed in to change notification settings - Fork 1
/
claims.go
65 lines (53 loc) · 1.57 KB
/
claims.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
package jwt
import (
"fmt"
"github.com/goccy/go-json"
"github.com/golang-jwt/jwt/v4"
"github.com/google/uuid"
"github.com/rumorsflow/rumors/v2/pkg/errs"
"time"
)
var _ jwt.Claims = (*UserClaims)(nil)
type UserClaims struct {
jwt.RegisteredClaims
Username string `json:"username,omitempty"`
Email string `json:"email,omitempty"`
Roles []string `json:"roles,omitempty"`
OTP bool `json:"otp"`
Meta json.RawMessage `json:"meta,omitempty"`
}
func RegisteredClaims(iss string, sub uuid.UUID, aud jwt.ClaimStrings, ttl time.Duration) jwt.RegisteredClaims {
now := jwt.TimeFunc()
return jwt.RegisteredClaims{
Issuer: iss,
Subject: sub.String(),
Audience: aud,
ExpiresAt: jwt.NewNumericDate(now.Add(ttl)),
IssuedAt: jwt.NewNumericDate(now),
NotBefore: jwt.NewNumericDate(now),
}
}
func (c UserClaims) UserID() uuid.UUID {
return uuid.MustParse(c.Subject)
}
func (c UserClaims) Valid() error {
vErr := &jwt.ValidationError{}
now := jwt.TimeFunc()
if !c.VerifyExpiresAt(now, true) {
delta := now.Sub(c.ExpiresAt.Time)
vErr.Inner = errs.Append(vErr.Inner, fmt.Errorf("%s by %s", jwt.ErrTokenExpired, delta))
vErr.Errors |= jwt.ValidationErrorExpired
}
if !c.VerifyIssuedAt(now, true) {
vErr.Inner = errs.Append(vErr.Inner, jwt.ErrTokenUsedBeforeIssued)
vErr.Errors |= jwt.ValidationErrorIssuedAt
}
if !c.VerifyNotBefore(now, true) {
vErr.Inner = errs.Append(vErr.Inner, jwt.ErrTokenNotValidYet)
vErr.Errors |= jwt.ValidationErrorNotValidYet
}
if vErr.Errors == 0 {
return nil
}
return vErr
}