forked from mdzio/ccu-jack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpauth.go
66 lines (53 loc) · 1.42 KB
/
httpauth.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
package main
import (
"net/http"
"github.com/mdzio/ccu-jack/rtcfg"
"github.com/mdzio/go-logging"
)
var (
logAuth = logging.Get("http-auth")
)
// HTTPAuthHandler wraps another http.Handler and authenticates an HTTP client.
type HTTPAuthHandler struct {
http.Handler
Store *rtcfg.Store
// Realm must only contain valid characters for an HTTP header value and no
// double quotes.
Realm string
}
func (h *HTTPAuthHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
name, passwd, ok := req.BasicAuth()
// read config
var allowAll bool
var user *rtcfg.User
h.Store.View(func(c *rtcfg.Config) error {
allowAll = len(c.Users) == 0
if !allowAll {
user = c.Authenticate(rtcfg.EndpointVEAP, name, passwd)
}
return nil
})
// if no user is configured, allow everything for every user
if allowAll {
h.Handler.ServeHTTP(rw, req)
return
}
// no credentials
if !ok {
logAuth.Tracef("Not authenticated: %s", req.RemoteAddr)
h.sendAuth(rw, req)
return
}
// check credentials
if user == nil {
logAuth.Warningf("Authentication request failed: address %s, user %s", req.RemoteAddr, name)
h.sendAuth(rw, req)
return
}
// credentials ok
h.Handler.ServeHTTP(rw, req)
}
func (h *HTTPAuthHandler) sendAuth(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("WWW-Authenticate", "Basic realm=\""+h.Realm+"\", charset=\"UTF-8\"")
http.Error(rw, "Unauthorized", http.StatusUnauthorized)
}