-
Notifications
You must be signed in to change notification settings - Fork 3
/
basic_test.go
101 lines (80 loc) · 2.29 KB
/
basic_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
101
package auth
import (
"encoding/base64"
"net/http"
"net/http/httptest"
"testing"
"gopkg.in/macaron.v1"
)
func Test_BasicAuth(t *testing.T) {
recorder := httptest.NewRecorder()
auth := "Basic " + base64.StdEncoding.EncodeToString([]byte("foo:bar"))
m := macaron.New()
m.Use(Basic("foo", "bar"))
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 foo" {
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 foo" {
t.Error("Auth failed, got: ", recorder.Body.String())
}
}
func Test_BasicFuncAuth(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 := "Basic " + base64.StdEncoding.EncodeToString([]byte(auth))
m := macaron.New()
m.Use(BasicFunc(func(username, password string) bool {
return (username == "foo" || username == "bar") && password == "spam"
}))
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)
}
}
}