middleware.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package fever // import "miniflux.app/v2/internal/fever"
  4. import (
  5. "context"
  6. "net/http"
  7. "miniflux.app/v2/internal/http/request"
  8. "miniflux.app/v2/internal/http/response/json"
  9. "miniflux.app/v2/internal/logger"
  10. "miniflux.app/v2/internal/storage"
  11. )
  12. type middleware struct {
  13. store *storage.Storage
  14. }
  15. func newMiddleware(s *storage.Storage) *middleware {
  16. return &middleware{s}
  17. }
  18. func (m *middleware) serve(next http.Handler) http.Handler {
  19. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  20. clientIP := request.ClientIP(r)
  21. apiKey := r.FormValue("api_key")
  22. if apiKey == "" {
  23. logger.Info("[Fever] [ClientIP=%s] No API key provided", clientIP)
  24. json.OK(w, r, newAuthFailureResponse())
  25. return
  26. }
  27. user, err := m.store.UserByFeverToken(apiKey)
  28. if err != nil {
  29. logger.Error("[Fever] %v", err)
  30. json.OK(w, r, newAuthFailureResponse())
  31. return
  32. }
  33. if user == nil {
  34. logger.Info("[Fever] [ClientIP=%s] No user found with this API key", clientIP)
  35. json.OK(w, r, newAuthFailureResponse())
  36. return
  37. }
  38. logger.Info("[Fever] [ClientIP=%s] User #%d is authenticated with user agent %q", clientIP, user.ID, r.UserAgent())
  39. m.store.SetLastLogin(user.ID)
  40. ctx := r.Context()
  41. ctx = context.WithValue(ctx, request.UserIDContextKey, user.ID)
  42. ctx = context.WithValue(ctx, request.UserTimezoneContextKey, user.Timezone)
  43. ctx = context.WithValue(ctx, request.IsAdminUserContextKey, user.IsAdmin)
  44. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  45. next.ServeHTTP(w, r.WithContext(ctx))
  46. })
  47. }