-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathhost_auth.go
56 lines (45 loc) · 1.24 KB
/
host_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
package ping
import (
"log"
"net/http"
"net/url"
"github.com/parkr/ping/jsv1"
)
func NewHostAuthMiddleware(allowedHosts []string, nextHandler http.Handler) http.Handler {
allowedHostsMap := make(map[string]bool, len(allowedHosts))
for _, allowedHost := range allowedHosts {
allowedHostsMap[allowedHost] = true
}
return hostAuthMiddleware{
allowedHosts: allowedHostsMap,
next: nextHandler,
}
}
type hostAuthMiddleware struct {
allowedHosts map[string]bool
next http.Handler
}
func (m hostAuthMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
referrer := r.Referer()
if referrer == "" {
log.Println("empty referrer")
jsv1.Error(w, http.StatusBadRequest, "empty referrer")
return
}
url, err := url.Parse(referrer)
if err != nil {
log.Println("invalid referrer:", sanitizeUserInput(referrer))
jsv1.Error(w, http.StatusInternalServerError, "Couldn't parse referrer: "+err.Error())
return
}
if !m.allowedHost(url.Host) {
log.Println("unauthorized host:", sanitizeUserInput(url.Host))
jsv1.Error(w, http.StatusUnauthorized, "unauthorized host")
return
}
m.next.ServeHTTP(w, r)
}
func (m hostAuthMiddleware) allowedHost(hostname string) bool {
_, ok := m.allowedHosts[hostname]
return ok
}