1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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, 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),
- }
- }
|