middleware.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. // BasicAuth handles HTTP basic authentication.
  20. func (m *middleware) serve(next http.Handler) http.Handler {
  21. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  22. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  23. clientIP := request.ClientIP(r)
  24. username, password, authOK := r.BasicAuth()
  25. if !authOK {
  26. logger.Debug("[API] No authentication headers sent")
  27. json.Unauthorized(w, r)
  28. return
  29. }
  30. if err := m.store.CheckPassword(username, password); err != nil {
  31. logger.Error("[API] [ClientIP=%s] Invalid username or password: %s", clientIP, username)
  32. json.Unauthorized(w, r)
  33. return
  34. }
  35. user, err := m.store.UserByUsername(username)
  36. if err != nil {
  37. logger.Error("[API] %v", err)
  38. json.ServerError(w, r, err)
  39. return
  40. }
  41. if user == nil {
  42. logger.Error("[API] [ClientIP=%s] User not found: %s", clientIP, username)
  43. json.Unauthorized(w, r)
  44. return
  45. }
  46. logger.Info("[API] User authenticated: %s", username)
  47. m.store.SetLastLogin(user.ID)
  48. ctx := r.Context()
  49. ctx = context.WithValue(ctx, request.UserIDContextKey, user.ID)
  50. ctx = context.WithValue(ctx, request.UserTimezoneContextKey, user.Timezone)
  51. ctx = context.WithValue(ctx, request.IsAdminUserContextKey, user.IsAdmin)
  52. ctx = context.WithValue(ctx, request.IsAuthenticatedContextKey, true)
  53. next.ServeHTTP(w, r.WithContext(ctx))
  54. })
  55. }