package auth import ( "encoding/base64" "net/http" "strings" ) type BasicAuthInfo struct { Group string Password string } type BasicAuth struct { users map[string]BasicAuthInfo } func (ba *BasicAuth) authenticate(user, password string) bool { rec, ok := ba.users[user] if !ok { return false } if rec.Password == password { return true } return false } func (ba *BasicAuth) DoAuth(w http.ResponseWriter, r *http.Request) (*AuthData, int) { w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`) s := strings.SplitN(r.Header.Get("Authorization"), " ", 2) if len(s) != 2 { return nil, http.StatusUnauthorized } b, err := base64.StdEncoding.DecodeString(s[1]) if err != nil { return nil, http.StatusUnauthorized } pair := strings.SplitN(string(b), ":", 2) if len(pair) != 2 { http.Error(w, "Not authorized", 401) return nil, http.StatusUnauthorized } if ba.authenticate(pair[0], pair[1]) { return &AuthData{User: pair[0], Group: ""}, http.StatusOK } return nil, http.StatusUnauthorized } func (ba *BasicAuth) AddUser(user, group, password string) error { ba.users[user] = BasicAuthInfo{ Password: password, Group: group, } return nil } func (ba *BasicAuth) DeleteUser(user string) error { delete(ba.users, user) return nil } func NewBasicAuth() AuthManager { return &BasicAuth{ users: make(map[string]BasicAuthInfo), } }