basicauth.go 967 B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package api
  2. import (
  3. "fmt"
  4. "net/http"
  5. "wkla.no-ip.biz/gogs/Willie/MsgService/MessageService/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. if !ok {
  13. basicAuthFailed(w, realm)
  14. return
  15. }
  16. idm := dao.GetIDM()
  17. salt, ok := idm.GetSalt(user)
  18. if !ok {
  19. basicAuthFailed(w, realm)
  20. return
  21. }
  22. pass = dao.BuildPasswordHash(pass, salt)
  23. if !idm.CheckUser(user, pass) {
  24. basicAuthFailed(w, realm)
  25. return
  26. }
  27. next.ServeHTTP(w, r)
  28. })
  29. }
  30. }
  31. func basicAuthFailed(w http.ResponseWriter, realm string) {
  32. w.Header().Add("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
  33. w.WriteHeader(http.StatusUnauthorized)
  34. }