fever.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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 // import "miniflux.app/middleware"
  5. import (
  6. "context"
  7. "net/http"
  8. "miniflux.app/http/request"
  9. "miniflux.app/http/response/json"
  10. "miniflux.app/logger"
  11. )
  12. // FeverAuth handles Fever API authentication.
  13. func (m *Middleware) FeverAuth(next http.Handler) http.Handler {
  14. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  15. apiKey := r.FormValue("api_key")
  16. user, err := m.store.UserByFeverToken(apiKey)
  17. if err != nil {
  18. logger.Error("[Middleware:Fever] %v", err)
  19. json.OK(w, r, map[string]int{"api_version": 3, "auth": 0})
  20. return
  21. }
  22. if user == nil {
  23. logger.Info("[Middleware:Fever] Fever authentication failure")
  24. json.OK(w, r, map[string]int{"api_version": 3, "auth": 0})
  25. return
  26. }
  27. logger.Info("[Middleware:Fever] User #%d is authenticated", user.ID)
  28. m.store.SetLastLogin(user.ID)
  29. ctx := r.Context()
  30. ctx = context.WithValue(ctx, request.UserIDContextKey, user.ID)
  31. ctx = context.WithValue(ctx, request.UserTimezoneContextKey, user.Timezone)
  32. ctx = context.WithValue(ctx, request.IsAdminUserContextKey, user.IsAdmin)
  33. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  34. next.ServeHTTP(w, r.WithContext(ctx))
  35. })
  36. }