middleware.go 1.6 KB

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