fever.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. // FeverMiddleware is the middleware that handles Fever API.
  12. type FeverMiddleware struct {
  13. store *storage.Storage
  14. }
  15. // Handler executes the middleware.
  16. func (f *FeverMiddleware) Handler(next http.Handler) http.Handler {
  17. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  18. logger.Debug("[Middleware:Fever]")
  19. apiKey := r.FormValue("api_key")
  20. user, err := f.store.UserByFeverToken(apiKey)
  21. if err != nil {
  22. logger.Error("[Fever] %v", err)
  23. w.Header().Set("Content-Type", "application/json")
  24. w.Write([]byte(`{"api_version": 3, "auth": 0}`))
  25. return
  26. }
  27. if user == nil {
  28. logger.Info("[Middleware:Fever] Fever authentication failure")
  29. w.Header().Set("Content-Type", "application/json")
  30. w.Write([]byte(`{"api_version": 3, "auth": 0}`))
  31. return
  32. }
  33. logger.Info("[Middleware:Fever] User #%d is authenticated", user.ID)
  34. f.store.SetLastLogin(user.ID)
  35. ctx := r.Context()
  36. ctx = context.WithValue(ctx, UserIDContextKey, user.ID)
  37. ctx = context.WithValue(ctx, UserTimezoneContextKey, user.Timezone)
  38. ctx = context.WithValue(ctx, IsAdminUserContextKey, user.IsAdmin)
  39. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  40. next.ServeHTTP(w, r.WithContext(ctx))
  41. })
  42. }
  43. // NewFeverMiddleware returns a new FeverMiddleware.
  44. func NewFeverMiddleware(s *storage.Storage) *FeverMiddleware {
  45. return &FeverMiddleware{store: s}
  46. }