basic_auth.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright 2017 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. "github.com/miniflux/miniflux/storage"
  10. )
  11. // BasicAuthMiddleware is the middleware for HTTP Basic authentication.
  12. type BasicAuthMiddleware struct {
  13. store *storage.Storage
  14. }
  15. // Handler executes the middleware.
  16. func (b *BasicAuthMiddleware) Handler(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  19. errorResponse := `{"error_message": "Not Authorized"}`
  20. username, password, authOK := r.BasicAuth()
  21. if !authOK {
  22. logger.Debug("[Middleware:BasicAuth] No authentication headers sent")
  23. w.WriteHeader(http.StatusUnauthorized)
  24. w.Write([]byte(errorResponse))
  25. return
  26. }
  27. if err := b.store.CheckPassword(username, password); err != nil {
  28. logger.Info("[Middleware:BasicAuth] Invalid username or password: %s", username)
  29. w.WriteHeader(http.StatusUnauthorized)
  30. w.Write([]byte(errorResponse))
  31. return
  32. }
  33. user, err := b.store.UserByUsername(username)
  34. if err != nil {
  35. logger.Error("[Middleware:BasicAuth] %v", err)
  36. w.WriteHeader(http.StatusInternalServerError)
  37. w.Write([]byte(errorResponse))
  38. return
  39. }
  40. if user == nil {
  41. logger.Info("[Middleware:BasicAuth] User not found: %s", username)
  42. w.WriteHeader(http.StatusUnauthorized)
  43. w.Write([]byte(errorResponse))
  44. return
  45. }
  46. logger.Info("[Middleware:BasicAuth] User authenticated: %s", username)
  47. b.store.SetLastLogin(user.ID)
  48. ctx := r.Context()
  49. ctx = context.WithValue(ctx, UserIDContextKey, user.ID)
  50. ctx = context.WithValue(ctx, UserTimezoneContextKey, user.Timezone)
  51. ctx = context.WithValue(ctx, IsAdminUserContextKey, user.IsAdmin)
  52. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  53. next.ServeHTTP(w, r.WithContext(ctx))
  54. })
  55. }
  56. // NewBasicAuthMiddleware returns a new BasicAuthMiddleware.
  57. func NewBasicAuthMiddleware(s *storage.Storage) *BasicAuthMiddleware {
  58. return &BasicAuthMiddleware{store: s}
  59. }