snap/auth/basic.go

59 lines
997 B
Go
Raw Normal View History

2018-01-24 02:26:26 +00:00
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
}
2018-02-07 22:25:00 +00:00
func (ba *BasicAuth) DoAuth(w http.ResponseWriter,r *http.Request) (string, bool) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
2018-01-24 02:26:26 +00:00
2018-02-07 22:25:00 +00:00
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
if len(s) != 2 {
return "", false
}
2018-01-24 02:26:26 +00:00
2018-02-07 22:25:00 +00:00
b, err := base64.StdEncoding.DecodeString(s[1])
if err != nil {
return "", false
}
2018-01-24 02:26:26 +00:00
2018-02-07 22:25:00 +00:00
pair := strings.SplitN(string(b), ":", 2)
if len(pair) != 2 {
http.Error(w, "Not authorized", 401)
return "", false
2018-01-24 02:26:26 +00:00
}
2018-02-07 22:25:00 +00:00
return pair[0], ba.authenticate(pair[0], pair[1])
2018-01-24 02:26:26 +00:00
}
func (ba *BasicAuth) AddUser(user, password string) {
ba.users[user] = password
}
func NewBasicAuth() *BasicAuth {
return &BasicAuth{
users: make(map[string]string),
}
}