servauth.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package servauth
  2. import (
  3. "log"
  4. "net/http"
  5. )
  6. // TODO: protect from bruteforce
  7. func BasicAuth(handler http.Handler, username, password, realm string) http.Handler {
  8. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  9. if username != "" {
  10. if realm == "" {
  11. realm = "Please enter username and password"
  12. }
  13. u, p, ok := r.BasicAuth()
  14. if !ok {
  15. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  16. w.WriteHeader(401)
  17. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  18. log.Printf("%s\n", err.Error())
  19. }
  20. return
  21. }
  22. if u != username {
  23. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  24. w.WriteHeader(401)
  25. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  26. log.Printf("%s\n", err.Error())
  27. }
  28. return
  29. }
  30. if p != password {
  31. w.Header().Set("WWW-Authenticate", `Basic realm="`+realm+`"`)
  32. w.WriteHeader(401)
  33. if _, err := w.Write([]byte("Unauthorised\n")); err != nil {
  34. log.Printf("%s\n", err.Error())
  35. }
  36. return
  37. }
  38. }
  39. handler.ServeHTTP(w, r)
  40. })
  41. }