-
Notifications
You must be signed in to change notification settings - Fork 1
/
token_test.go
66 lines (55 loc) · 1.45 KB
/
token_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
package scoutred_test
import (
"testing"
"time"
"github.com/dgrijalva/jwt-go"
"github.com/scoutred/scoutred-go"
)
func TestTokenHasExpired(t *testing.T) {
type tcase struct {
token string
hasExpired bool
}
fn := func(tc tcase) func(t *testing.T) {
return func(t *testing.T) {
t.Parallel()
expired, err := scoutred.TokenHasExpired(tc.token)
if err != nil {
t.Errorf("unexepected err: %v", err)
return
}
if expired != tc.hasExpired {
t.Errorf("expected %v got %v", tc.hasExpired, expired)
return
}
}
}
// genTokenExpires is a helper to generate tokens and set the ExpiresAt value
// using a provided daysFromNow offset
genTokenExpires := func(daysFromNow int) string {
tokenPast := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.StandardClaims{
ExpiresAt: time.Now().AddDate(0, 0, daysFromNow).Unix(), // subtract one day
})
// Sign and get the complete encoded token as a string using the secret
tokenString, err := tokenPast.SignedString([]byte("scoutred-secret"))
if err != nil {
t.Fatalf("unexepected err: %v", err)
}
return tokenString
}
// Auth handler will make sure that the route is never allowed, so
// no need to test for anonymous user.
tests := map[string]tcase{
"exired": {
token: genTokenExpires(-1),
hasExpired: true,
},
"not exired": {
token: genTokenExpires(1),
hasExpired: false,
},
}
for name, tc := range tests {
t.Run(name, fn(tc))
}
}