1
0

basicAuth.go 1.4 KB

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