basic_auth.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package middleware
  5. import (
  6. "context"
  7. "net/http"
  8. "github.com/miniflux/miniflux/logger"
  9. )
  10. // BasicAuth handles HTTP basic authentication.
  11. func (m *Middleware) BasicAuth(next http.Handler) http.Handler {
  12. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  13. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  14. errorResponse := `{"error_message": "Not Authorized"}`
  15. username, password, authOK := r.BasicAuth()
  16. if !authOK {
  17. logger.Debug("[Middleware:BasicAuth] No authentication headers sent")
  18. w.WriteHeader(http.StatusUnauthorized)
  19. w.Write([]byte(errorResponse))
  20. return
  21. }
  22. if err := m.store.CheckPassword(username, password); err != nil {
  23. logger.Info("[Middleware:BasicAuth] Invalid username or password: %s", username)
  24. w.WriteHeader(http.StatusUnauthorized)
  25. w.Write([]byte(errorResponse))
  26. return
  27. }
  28. user, err := m.store.UserByUsername(username)
  29. if err != nil {
  30. logger.Error("[Middleware:BasicAuth] %v", err)
  31. w.WriteHeader(http.StatusInternalServerError)
  32. w.Write([]byte(errorResponse))
  33. return
  34. }
  35. if user == nil {
  36. logger.Info("[Middleware:BasicAuth] User not found: %s", username)
  37. w.WriteHeader(http.StatusUnauthorized)
  38. w.Write([]byte(errorResponse))
  39. return
  40. }
  41. logger.Info("[Middleware:BasicAuth] User authenticated: %s", username)
  42. m.store.SetLastLogin(user.ID)
  43. ctx := r.Context()
  44. ctx = context.WithValue(ctx, UserIDContextKey, user.ID)
  45. ctx = context.WithValue(ctx, UserTimezoneContextKey, user.Timezone)
  46. ctx = context.WithValue(ctx, IsAdminUserContextKey, user.IsAdmin)
  47. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  48. next.ServeHTTP(w, r.WithContext(ctx))
  49. })
  50. }