-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
claims_test.go
95 lines (81 loc) · 2.04 KB
/
claims_test.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
package sjwt
import (
"testing"
"time"
)
type testStruc struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
}
func TestToClaims(t *testing.T) {
test := testStruc{
FirstName: "Billy",
LastName: "Mister",
}
claims, err := ToClaims(test)
if err != nil {
t.Error("Error ToClaims: ", err)
}
if !claims.Has("first_name") {
t.Error("Tried to get claim from struct. Non found")
}
}
func TestToStruct(t *testing.T) {
claims := New()
claims.Set("first_name", "Billy")
claims.Set("last_name", "Mister")
// Try to set claims into struct
var test testStruc
claims.ToStruct(&test)
if test.FirstName != "Billy" {
t.Error("Tried to get first name from test struct after running ToStruct and it failed")
}
}
func TestValidate(t *testing.T) {
// Validate just the claim
claims := New()
claims.SetIssuedAt(time.Now())
claims.SetNotBeforeAt(time.Now())
claims.SetExpiresAt(time.Now().Add(time.Hour))
err := claims.Validate()
if err != nil {
t.Error("Validate was not successful when it should be")
}
// Validate on parsed claims
token := claims.Generate([]byte(secretKey))
parsedClaims, err := Parse(token)
err = parsedClaims.Validate()
if err != nil {
t.Error("Validate was not successful on parsed claims when it should be")
}
}
func TestValidateExp(t *testing.T) {
// Succes
claims := New()
claims.SetExpiresAt(time.Now().Add(time.Hour))
err := claims.Validate()
if err != nil {
t.Error("Validate was not successful when it should be")
}
// Error
claims.SetExpiresAt(time.Now().Add(time.Hour * -1))
err = claims.Validate()
if err != ErrTokenHasExpired {
t.Error("Token should have expired")
}
}
func TestValidateNotBefore(t *testing.T) {
// Succes
claims := New()
claims.SetNotBeforeAt(time.Now())
err := claims.Validate()
if err != nil {
t.Error("Validate was not successful when it should be")
}
// Error
claims.SetNotBeforeAt(time.Now().Add(time.Hour))
err = claims.Validate()
if err != ErrTokenNotYetValid {
t.Error("Token should have failed due to token not being valid yet")
}
}