basic.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package auth
  2. import (
  3. "encoding/base64"
  4. "net/http"
  5. "strings"
  6. )
  7. type BasicAuthInfo struct {
  8. Group string
  9. Password string
  10. }
  11. type BasicAuth struct {
  12. users map[string]BasicAuthInfo
  13. }
  14. func (ba *BasicAuth) authenticate(user, password string) bool {
  15. rec, ok := ba.users[user]
  16. if !ok {
  17. return false
  18. }
  19. if rec.Password == password {
  20. return true
  21. }
  22. return false
  23. }
  24. func (ba *BasicAuth) DoAuth(w http.ResponseWriter, r *http.Request) (*AuthData, bool) {
  25. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  26. s := strings.SplitN(r.Header.Get("Authorization"), " ", 2)
  27. if len(s) != 2 {
  28. return nil, false
  29. }
  30. b, err := base64.StdEncoding.DecodeString(s[1])
  31. if err != nil {
  32. return nil, false
  33. }
  34. pair := strings.SplitN(string(b), ":", 2)
  35. if len(pair) != 2 {
  36. http.Error(w, "Not authorized", 401)
  37. return nil, false
  38. }
  39. if ba.authenticate(pair[0], pair[1]) {
  40. return &AuthData{User: pair[0], Group: ""}, true
  41. }
  42. return nil, false
  43. }
  44. func (ba *BasicAuth) AddUser(user, group, password string) error {
  45. ba.users[user] = BasicAuthInfo{
  46. Password: password,
  47. Group: group,
  48. }
  49. return nil
  50. }
  51. func (ba *BasicAuth) DeleteUser(user string) error {
  52. delete(ba.users, user)
  53. return nil
  54. }
  55. func NewBasicAuth() AuthManager {
  56. return &BasicAuth{
  57. users: make(map[string]BasicAuthInfo),
  58. }
  59. }