1
0

basicAuth.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package dynamicproxy
  2. import (
  3. "errors"
  4. "net/http"
  5. "strings"
  6. "imuslab.com/zoraxy/mod/auth"
  7. )
  8. /*
  9. BasicAuth.go
  10. This file handles the basic auth on proxy endpoints
  11. if RequireBasicAuth is set to true
  12. */
  13. func (h *ProxyHandler) handleBasicAuthRouting(w http.ResponseWriter, r *http.Request, pe *ProxyEndpoint) error {
  14. if len(pe.BasicAuthExceptionRules) > 0 {
  15. //Check if the current path matches the exception rules
  16. for _, exceptionRule := range pe.BasicAuthExceptionRules {
  17. if strings.HasPrefix(r.RequestURI, exceptionRule.PathPrefix) {
  18. //This path is excluded from basic auth
  19. return nil
  20. }
  21. }
  22. }
  23. proxyType := "vdir-auth"
  24. if pe.ProxyType == ProxyType_Subdomain {
  25. proxyType = "subd-auth"
  26. }
  27. u, p, ok := r.BasicAuth()
  28. if !ok {
  29. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  30. w.WriteHeader(401)
  31. return errors.New("unauthorized")
  32. }
  33. //Check for the credentials to see if there is one matching
  34. hashedPassword := auth.Hash(p)
  35. matchingFound := false
  36. for _, cred := range pe.BasicAuthCredentials {
  37. if u == cred.Username && hashedPassword == cred.PasswordHash {
  38. matchingFound = true
  39. break
  40. }
  41. }
  42. if !matchingFound {
  43. h.logRequest(r, false, 401, proxyType, pe.Domain)
  44. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  45. w.WriteHeader(401)
  46. return errors.New("unauthorized")
  47. }
  48. return nil
  49. }