snap/auth/basic.go

75 lines
1.4 KiB
Go
Raw Normal View History

2018-01-24 02:26:26 +00:00
package auth
import (
2021-01-19 03:23:52 +00:00
"encoding/base64"
2018-01-24 02:26:26 +00:00
"net/http"
"strings"
)
type BasicAuthInfo struct {
Group string
Password string
2018-01-24 02:26:26 +00:00
}
type BasicAuth struct {
users map[string]BasicAuthInfo
}
2018-01-24 02:26:26 +00:00
func (ba *BasicAuth) authenticate(user, password string) bool {
rec, ok := ba.users[user]
2018-01-24 02:26:26 +00:00
if !ok {
return false
}
if rec.Password == password {
2018-01-24 02:26:26 +00:00
return true
}
return false
}
func (ba *BasicAuth) DoAuth(w http.ResponseWriter, r *http.Request) (*AuthData, int) {
2018-02-07 22:25:00 +00:00
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 nil, http.StatusUnauthorized
2018-02-07 22:25:00 +00:00
}
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 nil, http.StatusUnauthorized
2018-02-07 22:25:00 +00:00
}
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 nil, http.StatusUnauthorized
2018-01-24 02:26:26 +00:00
}
2018-02-07 22:25:00 +00:00
if ba.authenticate(pair[0], pair[1]) {
return &AuthData{User: pair[0], Group: ""}, http.StatusOK
}
return nil, http.StatusUnauthorized
2018-01-24 02:26:26 +00:00
}
func (ba *BasicAuth) AddUser(user, group, password string) error {
ba.users[user] = BasicAuthInfo{
Password: password,
Group: group,
}
return nil
}
2018-01-24 02:26:26 +00:00
func (ba *BasicAuth) DeleteUser(user string) error {
delete(ba.users, user)
return nil
2018-01-24 02:26:26 +00:00
}
func NewBasicAuth() AuthManager {
2018-01-24 02:26:26 +00:00
return &BasicAuth{
users: make(map[string]BasicAuthInfo),
2018-01-24 02:26:26 +00:00
}
}