-
Notifications
You must be signed in to change notification settings - Fork 1
/
httpbasicauth_test.go
102 lines (89 loc) · 2.46 KB
/
httpbasicauth_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
102
package httpbasicauth
import (
"io"
"net/http"
"net/http/httptest"
"regexp"
"strings"
"testing"
)
func TestHandle(t *testing.T) {
handler := http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "YOLO!")
},
)
creds := SimpleCredentialMap{"foo": "bar"}
// creds := map[string]string{"foo": "bar"}
authhandler := Handle(creds, "Restricted zone")(handler)
tests := []struct {
name string
user string
password string
expectedResponseCode int
expectedResponseBody string
expectedRealm string
}{
{
name: "auth with wrong user",
user: "f00",
password: "bar",
expectedResponseCode: 401,
expectedRealm: "Restricted zone",
expectedResponseBody: "401 Unauthorized",
},
{
name: "auth with wrong password",
user: "foo",
password: "b@r",
expectedResponseCode: 401,
expectedRealm: "Restricted zone",
expectedResponseBody: "401 Unauthorized",
},
{
name: "auth without creds",
expectedResponseCode: 401,
expectedRealm: "Restricted zone",
expectedResponseBody: "401 Unauthorized",
},
{
name: "auth with correct creds",
user: "foo",
password: "bar",
expectedResponseCode: 200,
expectedResponseBody: "YOLO!",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "/", nil)
if err != nil {
t.Fatal(err)
}
if tt.user != "" {
req.SetBasicAuth(tt.user, tt.password)
}
rr := httptest.NewRecorder()
authhandler.ServeHTTP(rr, req)
// check realm
if rr.Code != http.StatusOK {
wwwauth := getrealm(rr)
if wwwauth == "" || wwwauth != tt.expectedRealm {
t.Fatalf("Unexpected realm, got %v, expected = %v", wwwauth, tt.expectedRealm)
}
}
if tt.expectedResponseCode != rr.Code {
t.Fatalf("Wrong status code, got %v, expected = %v", rr.Code, tt.expectedResponseCode)
}
responseBody := strings.TrimSpace(rr.Body.String())
if responseBody != tt.expectedResponseBody {
t.Errorf("Unexpected body: got %v, want %v", responseBody, tt.expectedResponseBody)
}
})
}
}
func getrealm(r http.ResponseWriter) string {
re := regexp.MustCompile(`^Basic realm="(.+?)"$`)
wwwauth := r.Header().Get("WWW-Authenticate")
return re.FindStringSubmatch(wwwauth)[1]
}