-
Notifications
You must be signed in to change notification settings - Fork 7
/
basic.go
49 lines (37 loc) · 887 Bytes
/
basic.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
package main
import (
"encoding/base64"
"net/http"
"strings"
)
type User struct {
UserId string
Password string
}
func basicAuth(w http.ResponseWriter, r *http.Request, users []User) bool {
var auth = r.Header.Get("Proxy-Authorization")
if ms := strings.Split(auth, " "); len(ms) == 2 && ms[0] == "Basic" {
// check user:password
up, err := base64.StdEncoding.DecodeString(ms[1])
if err == nil {
if ms := strings.Split(string(up), ":"); len(ms) == 2 {
var user, password = ms[0], ms[1]
var ok = false
for _, u := range users {
if u.UserId == user && u.Password == password {
ok = true
break
}
}
if ok {
return true
}
}
}
w.WriteHeader(http.StatusForbidden)
} else {
w.WriteHeader(http.StatusProxyAuthRequired)
w.Header().Set("Proxy-Authenticate", `Basic realm="Http Proxy"`)
}
return false
}