basicauth.go 933 B

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