-
Notifications
You must be signed in to change notification settings - Fork 50
/
auth.go
47 lines (37 loc) · 853 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
45
46
47
package main
import (
"encoding/base64"
"net/http"
"strings"
)
func BasicAuth(fn http.HandlerFunc, cred string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if cred == "" {
fn(w, r)
return
}
if checkAuth(w, r, cred) {
fn(w, r)
return
}
w.Header().Set("WWW-Authenticate", `Basic realm="Authenticate"`)
w.WriteHeader(401)
w.Write([]byte("401 Unauthorized\n"))
}
}
func checkAuth(w http.ResponseWriter, r *http.Request, cred string) bool {
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return false
}
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return false
}
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
return false
}
user := strings.Split(cred, ":")
return pair[0] == user[0] && pair[1] == user[1]
}