middleware.go 3.8 KB

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