middleware.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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 api // import "miniflux.app/api"
  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) handleCORS(next http.Handler) http.Handler {
  20. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  21. w.Header().Set("Access-Control-Allow-Origin", "*")
  22. w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
  23. w.Header().Set("Access-Control-Allow-Headers", "X-Auth-Token")
  24. if r.Method == http.MethodOptions {
  25. w.WriteHeader(http.StatusOK)
  26. return
  27. }
  28. next.ServeHTTP(w, r)
  29. })
  30. }
  31. func (m *middleware) apiKeyAuth(next http.Handler) http.Handler {
  32. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  33. clientIP := request.ClientIP(r)
  34. token := r.Header.Get("X-Auth-Token")
  35. if token == "" {
  36. logger.Debug("[API][TokenAuth] [ClientIP=%s] No API Key provided, go to the next middleware", clientIP)
  37. next.ServeHTTP(w, r)
  38. return
  39. }
  40. user, err := m.store.UserByAPIKey(token)
  41. if err != nil {
  42. logger.Error("[API][TokenAuth] %v", err)
  43. json.ServerError(w, r, err)
  44. return
  45. }
  46. if user == nil {
  47. logger.Error("[API][TokenAuth] [ClientIP=%s] No user found with the given API key", clientIP)
  48. json.Unauthorized(w, r)
  49. return
  50. }
  51. logger.Info("[API][TokenAuth] [ClientIP=%s] User authenticated: %s", clientIP, user.Username)
  52. m.store.SetLastLogin(user.ID)
  53. m.store.SetAPIKeyUsedTimestamp(user.ID, token)
  54. ctx := r.Context()
  55. ctx = context.WithValue(ctx, request.UserIDContextKey, user.ID)
  56. ctx = context.WithValue(ctx, request.UserTimezoneContextKey, user.Timezone)
  57. ctx = context.WithValue(ctx, request.IsAdminUserContextKey, user.IsAdmin)
  58. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  59. next.ServeHTTP(w, r.WithContext(ctx))
  60. })
  61. }
  62. func (m *middleware) basicAuth(next http.Handler) http.Handler {
  63. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  64. if request.IsAuthenticated(r) {
  65. next.ServeHTTP(w, r)
  66. return
  67. }
  68. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  69. clientIP := request.ClientIP(r)
  70. username, password, authOK := r.BasicAuth()
  71. if !authOK {
  72. logger.Debug("[API][BasicAuth] [ClientIP=%s] No authentication headers sent", clientIP)
  73. json.Unauthorized(w, r)
  74. return
  75. }
  76. if username == "" || password == "" {
  77. logger.Error("[API][BasicAuth] [ClientIP=%s] Empty username or password", clientIP)
  78. json.Unauthorized(w, r)
  79. return
  80. }
  81. if err := m.store.CheckPassword(username, password); err != nil {
  82. logger.Error("[API][BasicAuth] [ClientIP=%s] Invalid username or password: %s", clientIP, username)
  83. json.Unauthorized(w, r)
  84. return
  85. }
  86. user, err := m.store.UserByUsername(username)
  87. if err != nil {
  88. logger.Error("[API][BasicAuth] %v", err)
  89. json.ServerError(w, r, err)
  90. return
  91. }
  92. if user == nil {
  93. logger.Error("[API][BasicAuth] [ClientIP=%s] User not found: %s", clientIP, username)
  94. json.Unauthorized(w, r)
  95. return
  96. }
  97. logger.Info("[API][BasicAuth] [ClientIP=%s] User authenticated: %s", clientIP, username)
  98. m.store.SetLastLogin(user.ID)
  99. ctx := r.Context()
  100. ctx = context.WithValue(ctx, request.UserIDContextKey, user.ID)
  101. ctx = context.WithValue(ctx, request.UserTimezoneContextKey, user.Timezone)
  102. ctx = context.WithValue(ctx, request.IsAdminUserContextKey, user.IsAdmin)
  103. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  104. next.ServeHTTP(w, r.WithContext(ctx))
  105. })
  106. }