-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasicauth.go
45 lines (34 loc) · 971 Bytes
/
basicauth.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
package router
import (
"context"
"net/http"
)
type usernamekey string
const UsernameKey = usernamekey("username")
type UserData struct {
username, password string
}
func newUserData(username, password string) *UserData {
return &UserData{username, password}
}
func (ud *UserData) Username() string {
return ud.username
}
func (ud *UserData) Password() string {
return ud.password
}
type UserChecker = func(*UserData) bool
func BasicAuth(userChecker UserChecker) Middleware {
return func(next HttpHandler) HttpHandler {
return func(w http.ResponseWriter, r *http.Request) {
performBasicAuth(w, r, userChecker, next)
}
}
}
func performBasicAuth(w http.ResponseWriter, r *http.Request, userChecker UserChecker, next HttpHandler) {
if user, pass, ok := r.BasicAuth(); ok && userChecker(newUserData(user, pass)) {
next(w, r.WithContext(context.WithValue(r.Context(), UsernameKey, user)))
return
}
http.Error(w, "", http.StatusUnauthorized)
}