basic_auth.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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
  5. import (
  6. "context"
  7. "net/http"
  8. "github.com/miniflux/miniflux/http/response/json"
  9. "github.com/miniflux/miniflux/logger"
  10. )
  11. // BasicAuth handles HTTP basic authentication.
  12. func (m *Middleware) BasicAuth(next http.Handler) http.Handler {
  13. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  14. w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
  15. username, password, authOK := r.BasicAuth()
  16. if !authOK {
  17. logger.Debug("[Middleware:BasicAuth] No authentication headers sent")
  18. json.Unauthorized(w)
  19. return
  20. }
  21. if err := m.store.CheckPassword(username, password); err != nil {
  22. logger.Info("[Middleware:BasicAuth] Invalid username or password: %s", username)
  23. json.Unauthorized(w)
  24. return
  25. }
  26. user, err := m.store.UserByUsername(username)
  27. if err != nil {
  28. logger.Error("[Middleware:BasicAuth] %v", err)
  29. json.ServerError(w, err)
  30. return
  31. }
  32. if user == nil {
  33. logger.Info("[Middleware:BasicAuth] User not found: %s", username)
  34. json.Unauthorized(w)
  35. return
  36. }
  37. logger.Info("[Middleware:BasicAuth] User authenticated: %s", username)
  38. m.store.SetLastLogin(user.ID)
  39. ctx := r.Context()
  40. ctx = context.WithValue(ctx, UserIDContextKey, user.ID)
  41. ctx = context.WithValue(ctx, UserTimezoneContextKey, user.Timezone)
  42. ctx = context.WithValue(ctx, IsAdminUserContextKey, user.IsAdmin)
  43. ctx = context.WithValue(ctx, IsAuthenticatedContextKey, true)
  44. next.ServeHTTP(w, r.WithContext(ctx))
  45. })
  46. }