snap/auth/basic.go

59 lines
997 B
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(w http.ResponseWriter,r *http.Request) (string, bool) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
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 {
http.Error(w, "Not authorized", 401)
return "", false
}
return pair[0], ba.authenticate(pair[0], pair[1])
}
func (ba *BasicAuth) AddUser(user, password string) {
ba.users[user] = password
}
func NewBasicAuth() *BasicAuth {
return &BasicAuth{
users: make(map[string]string),
}
}