Fieldnotes app backend

auth.go 690B

1234567891011121314151617181920212223242526272829
  1. package main
  2. import (
  3. "fmt"
  4. "net/http"
  5. )
  6. func BasicAuth(username, password string) func(http.Handler) http.Handler {
  7. return func(next http.Handler) http.Handler {
  8. fn := func(w http.ResponseWriter, r *http.Request) {
  9. reqUsername, reqPassword, ok := r.BasicAuth()
  10. if !ok {
  11. unauthorized(w)
  12. return
  13. }
  14. if reqUsername != username || password != reqPassword {
  15. unauthorized(w)
  16. return
  17. }
  18. next.ServeHTTP(w, r)
  19. }
  20. return http.HandlerFunc(fn)
  21. }
  22. }
  23. func unauthorized(w http.ResponseWriter) {
  24. w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="fieldnotes-server"`))
  25. http.Error(w, http.StatusText(http.StatusUnauthorized), http.StatusUnauthorized)
  26. }