-
Notifications
You must be signed in to change notification settings - Fork 3
/
bearer_test.go
100 lines (79 loc) · 2.11 KB
/
bearer_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
96
97
98
99
100
package auth
import (
"net/http"
"net/http/httptest"
"testing"
"gopkg.in/macaron.v1"
)
func Test_BearerAuth(t *testing.T) {
recorder := httptest.NewRecorder()
auth := "Bearer foobar"
m := macaron.New()
m.Use(Bearer("foobar"))
m.Use(func(res http.ResponseWriter, req *http.Request, u User) {
res.Write([]byte("hello " + u))
})
r, _ := http.NewRequest("GET", "foo", nil)
m.ServeHTTP(recorder, r)
if recorder.Code != 401 {
t.Error("Response not 401")
}
if recorder.Body.String() == "hello " {
t.Error("Auth block failed")
}
recorder = httptest.NewRecorder()
r.Header.Set("Authorization", auth)
m.ServeHTTP(recorder, r)
if recorder.Code == 401 {
t.Error("Response is 401")
}
if recorder.Body.String() != "hello " {
t.Error("Auth failed, got: ", recorder.Body.String())
}
}
func Test_BearerFuncAuth(t *testing.T) {
for auth, valid := range map[string]bool{
"foo:spam": true,
"bar:spam": true,
"foo:eggs": false,
"bar:eggs": false,
"baz:spam": false,
"foo:spam:extra": false,
"dummy:": false,
"dummy": false,
"": false,
} {
recorder := httptest.NewRecorder()
encoded := "Bearer " + auth
m := macaron.New()
m.Use(BearerFunc(func(token string) bool {
return valid
}))
m.Use(func(res http.ResponseWriter, req *http.Request) {
res.Write([]byte("hello"))
})
r, _ := http.NewRequest("GET", "foo", nil)
m.ServeHTTP(recorder, r)
if recorder.Code != 401 {
t.Error("Response not 401, params:", auth)
}
if recorder.Body.String() == "hello" {
t.Error("Auth block failed, params:", auth)
}
recorder = httptest.NewRecorder()
r.Header.Set("Authorization", encoded)
m.ServeHTTP(recorder, r)
if valid && recorder.Code == 401 {
t.Error("Response is 401, params:", auth)
}
if !valid && recorder.Code != 401 {
t.Error("Response not 401, params:", auth)
}
if valid && recorder.Body.String() != "hello" {
t.Error("Auth failed, got: ", recorder.Body.String(), "params:", auth)
}
if !valid && recorder.Body.String() == "hello" {
t.Error("Auth block failed, params:", auth)
}
}
}