basic_auth.go 1.8 KB

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