-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbasicauth_test.go
81 lines (69 loc) · 1.75 KB
/
basicauth_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
package basicauth
import (
"encoding/json"
"net/http"
"testing"
)
func TestNew(t *testing.T) {
type (
role string
user struct {
Username string
Password string
Roles []role
}
)
users := []user{
{"kataras", "kataras_pass", []role{"admin"}},
{"george", "george_pass", []role{}},
}
opts := Options{
Realm: DefaultRealm,
Allow: AllowUsers(users),
OnLogoutClearContext: true,
}
auth := New(opts)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, ok := GetUser(r).(user) // test get user by sending it as a json response.
if !ok {
t.Fatal("unexpected user type")
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
err := json.NewEncoder(w).Encode(u)
if err != nil {
t.Fatal(err)
}
// test OnLogoutClearContext
r = Logout(r)
username, password, ok := r.BasicAuth()
if ok {
t.Fatalf("expected request's basic authentication credentials to be removed but got: %s:%s", username, password)
}
v := GetUser(r)
if v != nil {
t.Fatalf("expected a nil user as its stored credentials removed but got: %#+v", v)
}
})
var tests = []struct {
username, password string
ok bool
user interface{}
}{
{"kataras", "kataras_pass", true, users[0]},
{"george", "george_pass", true, users[1]},
{"kataras", "invalid_pass", false, nil},
{"george", "invalid_pass", false, nil},
{"invalid", "invalid_pass", false, nil},
}
for i, tt := range tests {
te := testHandler(t, auth(handler), http.MethodGet, "/",
withRequestID(i), withBasicAuth(tt.username, tt.password),
)
if tt.ok {
te.statusCode(http.StatusOK)
te.jsonEq(tt.user)
} else {
te.statusCode(http.StatusUnauthorized)
}
}
}