auth.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package gin
  2. import (
  3. "crypto/subtle"
  4. "encoding/base64"
  5. "errors"
  6. "sort"
  7. )
  8. type (
  9. BasicAuthPair struct {
  10. Code string
  11. User string
  12. }
  13. Account struct {
  14. User string
  15. Password string
  16. }
  17. Accounts []Account
  18. Pairs []BasicAuthPair
  19. )
  20. func (a Pairs) Len() int { return len(a) }
  21. func (a Pairs) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  22. func (a Pairs) Less(i, j int) bool { return a[i].Code < a[j].Code }
  23. func processCredentials(accounts Accounts) (Pairs, error) {
  24. if len(accounts) == 0 {
  25. return nil, errors.New("Empty list of authorized credentials.")
  26. }
  27. pairs := make(Pairs, 0, len(accounts))
  28. for _, account := range accounts {
  29. if len(account.User) == 0 || len(account.Password) == 0 {
  30. return nil, errors.New("User or password is empty")
  31. }
  32. base := account.User + ":" + account.Password
  33. code := "Basic " + base64.StdEncoding.EncodeToString([]byte(base))
  34. pairs = append(pairs, BasicAuthPair{code, account.User})
  35. }
  36. // We have to sort the credentials in order to use bsearch later.
  37. sort.Sort(pairs)
  38. return pairs, nil
  39. }
  40. func searchCredential(pairs Pairs, auth string) string {
  41. if len(auth) == 0 {
  42. return ""
  43. }
  44. // Search user in the slice of allowed credentials
  45. r := sort.Search(len(pairs), func(i int) bool { return pairs[i].Code >= auth })
  46. if r < len(pairs) && subtle.ConstantTimeCompare([]byte(pairs[r].Code), []byte(auth)) == 1 {
  47. // user is allowed, set UserId to key "user" in this context, the userId can be read later using
  48. // c.Get("user"
  49. return pairs[r].User
  50. } else {
  51. return ""
  52. }
  53. }
  54. // Implements a basic Basic HTTP Authorization. It takes as argument a map[string]string where
  55. // the key is the user name and the value is the password.
  56. func BasicAuth(accounts Accounts) HandlerFunc {
  57. pairs, err := processCredentials(accounts)
  58. if err != nil {
  59. panic(err)
  60. }
  61. return func(c *Context) {
  62. // Search user in the slice of allowed credentials
  63. user := searchCredential(pairs, c.Req.Header.Get("Authorization"))
  64. if len(user) == 0 {
  65. // Credentials doesn't match, we return 401 Unauthorized and abort request.
  66. c.Writer.Header().Set("WWW-Authenticate", "Basic realm=\"Authorization Required\"")
  67. c.Fail(401, errors.New("Unauthorized"))
  68. } else {
  69. // user is allowed, set UserId to key "user" in this context, the userId can be read later using
  70. // c.Get("user")
  71. c.Set("user", user)
  72. }
  73. }
  74. }