-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken_test.go
93 lines (72 loc) · 2.14 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
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
package token
import (
"encoding/base64"
"fmt"
"testing"
"time"
)
var (
secret = "secretForTesting"
id = "[email protected]"
)
func TestValidToken(t *testing.T) {
g := NewTokenHmacSha(secret)
token := g.Generate(id)
t.Log("Token Generated ", token)
valid, actualId, issue := g.Valid(token, 10*time.Minute)
if !valid {
t.Error("Token is not valid: Expected to be valid")
}
if actualId != id {
t.Errorf("Id is not the same, %v != %v", actualId, id)
}
t.Logf("Token Valid=%v Id=%v Issue=%v", valid, actualId, issue)
}
func TestValidAndNotExpiredToken(t *testing.T) {
g := NewTokenHmacSha(secret)
token := g.Generate(id)
t.Log("Token Generated ", token)
time.Sleep(100 * time.Millisecond)
valid, actualId, issue := g.Valid(token, 10*time.Minute)
if !valid {
t.Error("Token is not valid: Expected to be valid")
}
valid, actualId, issue = g.Valid(token, 1*time.Second)
if !valid {
t.Error("Token is not valid: Expected to be valid")
}
t.Logf("Token Valid=%v Id=%v Issue=%v", valid, actualId, issue)
valid, actualId, issue = g.Valid(token, 50*time.Millisecond)
if valid {
t.Error("Token should be invalid!!")
}
t.Logf("Token Valid=%v Id=%v Issue=%v", valid, actualId, issue)
}
func TestInvalidEncode(t *testing.T) {
g := NewTokenHmacSha(secret)
token := "badData"
valid, _, _ := g.Valid(token, 10*time.Minute)
if valid {
t.Error("Token is valid: Expected not valid, because bad encoding")
}
}
func TestInvalidFormatEncode(t *testing.T) {
g := NewTokenHmacSha(secret)
raw := "badstring"
token := base64.URLEncoding.EncodeToString([]byte(raw))
valid, _, _ := g.Valid(token, 10*time.Minute)
if valid {
t.Error("Token is valid: Expected not valid, because bad format")
}
}
func TestInvalidTimestamp(t *testing.T) {
g := NewTokenHmacSha(secret)
hash := base64.URLEncoding.EncodeToString([]byte("test"))
rnd := base64.URLEncoding.EncodeToString([]byte("test1"))
ts := base64.URLEncoding.EncodeToString([]byte("badtime"))
token := fmt.Sprintf("%s.%s.%s.%s", hash, rnd, id, ts)
valid, _, _ := g.Valid(token, 10*time.Minute)
if valid {
t.Error("Token is valid: Expected not valid, because bad timestamp")
}
}