This repository has been archived by the owner on Sep 19, 2019. It is now read-only.
/
key_auth.go
121 lines (104 loc) · 2.43 KB
/
key_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
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package httphandlers
import (
"bytes"
"encoding/base64"
"fmt"
"net"
"net/http"
"strings"
)
type KeyAuth struct {
Handler http.Handler
UnauthorizedHandler http.Handler
Keys map[string]bool
ValidateFunc func(key string) bool
PostAuthFunc func(key string, valid bool, w http.ResponseWriter, r *http.Request) bool
AuthorizeAll bool
AuthorizedNetworks []net.IPNet
HeaderName string
BasicAuthRealm string
}
func (h KeyAuth) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if h.UnauthorizedHandler == nil {
h.UnauthorizedHandler = http.HandlerFunc(defaultKeyAuthUnauthorizedHandler)
}
key, valid := h.authenticate(r)
if h.PostAuthFunc != nil && h.PostAuthFunc(key, valid, w, r) == false {
return
}
if !valid {
h.unauthorized(w, r)
return
}
h.Handler.ServeHTTP(w, r)
}
func (h KeyAuth) authenticate(r *http.Request) (key string, valid bool) {
if h.AuthorizeAll {
valid = true
return
}
if len(h.AuthorizedNetworks) > 0 {
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
panic(err)
}
ip := net.ParseIP(host)
for _, network := range h.AuthorizedNetworks {
if network.Contains(ip) {
valid = true
return
}
}
}
if h.HeaderName != "" {
key = r.Header.Get(h.HeaderName)
if key != "" {
if enabled, ok := h.Keys[key]; ok {
valid = enabled
return
}
if h.ValidateFunc != nil {
valid = h.ValidateFunc(key)
return
}
}
}
if h.BasicAuthRealm != "" {
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, basicAuthScheme) {
return
}
decoded, err := base64.StdEncoding.DecodeString(auth[len(basicAuthScheme):])
if err != nil {
return
}
creds := bytes.SplitN(decoded, []byte(":"), 2)
if len(creds) != 2 {
return
}
key = string(creds[0])
if key == "" {
key = string(creds[1])
}
if key != "" {
if enabled, ok := h.Keys[key]; ok {
valid = enabled
return
}
if h.ValidateFunc != nil {
valid = h.ValidateFunc(key)
return
}
}
}
return
}
func (h KeyAuth) unauthorized(w http.ResponseWriter, r *http.Request) {
if h.BasicAuthRealm != "" {
w.Header().Set("WWW-Authenticate", fmt.Sprintf("Basic realm=%q", h.BasicAuthRealm))
}
h.UnauthorizedHandler.ServeHTTP(w, r)
}
func defaultKeyAuthUnauthorizedHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
}