basic_auth.go 699 B

12345678910111213141516171819
  1. package api
  2. import (
  3. "crypto/subtle"
  4. macaron "gopkg.in/macaron.v1"
  5. )
  6. // BasicAuthenticatedRequest parses the provided HTTP request for basic authentication credentials
  7. // and returns true if the provided credentials match the expected username and password.
  8. // Returns false if the request is unauthenticated.
  9. // Uses constant-time comparison in order to mitigate timing attacks.
  10. func BasicAuthenticatedRequest(req macaron.Request, expectedUser, expectedPass string) bool {
  11. user, pass, ok := req.BasicAuth()
  12. if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(expectedUser)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(expectedPass)) != 1 {
  13. return false
  14. }
  15. return true
  16. }