forked from pivotal-cf/brokerapi
-
Notifications
You must be signed in to change notification settings - Fork 0
/
auth.go
44 lines (35 loc) · 992 Bytes
/
auth.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
package auth
import "net/http"
type Wrapper struct {
username string
password string
}
func NewWrapper(username, password string) *Wrapper {
return &Wrapper{
username: username,
password: password,
}
}
const notAuthorized = "Not Authorized"
func (wrapper *Wrapper) Wrap(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !authorized(wrapper, r) {
http.Error(w, notAuthorized, http.StatusUnauthorized)
return
}
handler.ServeHTTP(w, r)
})
}
func (wrapper *Wrapper) WrapFunc(handlerFunc http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !authorized(wrapper, r) {
http.Error(w, notAuthorized, http.StatusUnauthorized)
return
}
handlerFunc(w, r)
})
}
func authorized(wrapper *Wrapper, r *http.Request) bool {
username, password, isOk := r.BasicAuth()
return isOk && username == wrapper.username && password == wrapper.password
}