basicauth.go 897 B

123456789101112131415161718192021222324252627282930313233
  1. package api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "github.com/willie68/schematic-service-go/dao"
  6. )
  7. // BasicAuth implements a simple middleware handler for adding basic http auth to a route.
  8. func BasicAuth(realm string) func(next http.Handler) http.Handler {
  9. return func(next http.Handler) http.Handler {
  10. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  11. user, pass, ok := r.BasicAuth()
  12. pass = dao.BuildPasswordHash(pass)
  13. if !ok {
  14. basicAuthFailed(w, realm)
  15. return
  16. }
  17. fmt.Printf("user: %s, password: %s\n", user, pass)
  18. if !dao.GetStorage().CheckUser(user, pass) {
  19. basicAuthFailed(w, realm)
  20. return
  21. }
  22. next.ServeHTTP(w, r)
  23. })
  24. }
  25. }
  26. func basicAuthFailed(w http.ResponseWriter, realm string) {
  27. w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
  28. w.WriteHeader(http.StatusUnauthorized)
  29. }