75 lines
1.3 KiB
Go
75 lines
1.3 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"encoding/base64"
|
|
)
|
|
|
|
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, bool) {
|
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
|
|
|
s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
|
|
if len(s) != 2 {
|
|
return nil, false
|
|
}
|
|
|
|
b, err := base64.StdEncoding.DecodeString(s[1])
|
|
if err != nil {
|
|
return nil, false
|
|
}
|
|
|
|
pair := strings.SplitN(string(b), ":", 2)
|
|
if len(pair) != 2 {
|
|
http.Error(w, "Not authorized", 401)
|
|
return nil, false
|
|
}
|
|
|
|
if ba.authenticate(pair[0], pair[1]) {
|
|
return &AuthData{User: pair[0], Group: ""}, true
|
|
}
|
|
|
|
return nil, false
|
|
}
|
|
|
|
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),
|
|
}
|
|
}
|