68 lines
1.1 KiB
Go
68 lines
1.1 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"encoding/base64"
|
|
)
|
|
|
|
type BasicAuth struct {
|
|
users map[string]string
|
|
}
|
|
|
|
|
|
func (ba *BasicAuth) authenticate(user, password string) bool {
|
|
pass,ok := ba.users[user]
|
|
if !ok {
|
|
return false
|
|
}
|
|
|
|
if pass == password {
|
|
return true
|
|
}
|
|
|
|
return false
|
|
}
|
|
|
|
func (ba *BasicAuth) DoAuth(h http.HandlerFunc) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
|
|
|
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
|
if len(s) != 2 {
|
|
http.Error(w, "Not authorized", 401)
|
|
return
|
|
}
|
|
|
|
b, err := base64.StdEncoding.DecodeString(s[1])
|
|
if err != nil {
|
|
http.Error(w, err.Error(), 401)
|
|
return
|
|
}
|
|
|
|
pair := strings.SplitN(string(b), ":", 2)
|
|
if len(pair) != 2 {
|
|
http.Error(w, "Not authorized", 401)
|
|
return
|
|
}
|
|
|
|
if !ba.authenticate(pair[0], pair[1]) {
|
|
http.Error(w, "Not authorized", 401)
|
|
return
|
|
}
|
|
|
|
h.ServeHTTP(w, r)
|
|
}
|
|
}
|
|
|
|
|
|
func (ba *BasicAuth) AddUser(user, password string) {
|
|
ba.users[user] = password
|
|
}
|
|
|
|
func NewBasicAuth() *BasicAuth {
|
|
return &BasicAuth{
|
|
users: make(map[string]string),
|
|
}
|
|
}
|