-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
claims.go
60 lines (49 loc) · 1.18 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
package sjwt
import (
"encoding/json"
"time"
)
// Claims is the main container for our body information
type Claims map[string]interface{}
// New will initiate a new claims
func New() *Claims {
return &Claims{}
}
// ToClaims takes in an interface and unmarshals it to claims
func ToClaims(struc interface{}) (Claims, error) {
strucBytes, _ := json.Marshal(struc)
var claims Claims
err := json.Unmarshal(strucBytes, &claims)
if err != nil {
return nil, err
}
return claims, nil
}
// ToStruct takes your claims and sets value to struct
func (c Claims) ToStruct(struc interface{}) error {
claimsBytes, _ := json.Marshal(c)
err := json.Unmarshal(claimsBytes, struc)
if err != nil {
return err
}
return nil
}
// Validate checks expiration and not before times
func (c Claims) Validate() error {
now := time.Now().Unix()
// Check if not before at is set and if current time hasnt started yet
if c.Has(NotBeforeAt) {
nbf, _ := c.GetNotBeforeAt()
if now < nbf {
return ErrTokenNotYetValid
}
}
// Check if expiration at is set and if current time is passed
if c.Has(ExpiresAt) {
exp, _ := c.GetExpiresAt()
if now >= exp {
return ErrTokenHasExpired
}
}
return nil
}