middleware.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from typing import Callable
  2. from django.conf import settings
  3. from axes.helpers import get_lockout_response
  4. class AxesMiddleware:
  5. """
  6. Middleware that calculates necessary HTTP request attributes for attempt monitoring
  7. and maps lockout signals into readable HTTP 403 Forbidden responses.
  8. If a project uses ``django rest framework`` then the middleware updates the
  9. request and checks whether the limit has been exceeded. It's needed only
  10. for integration with DRF because it uses its own request object.
  11. This middleware recognizes a logout monitoring flag in the request and
  12. and uses the ``axes.helpers.get_lockout_response`` handler for returning
  13. customizable and context aware lockout message to the end user if necessary.
  14. To customize the lockout handling behaviour further, you can subclass this middleware
  15. and change the ``__call__`` method to your own liking.
  16. Please see the following configuration flags before customizing this handler:
  17. - ``AXES_LOCKOUT_TEMPLATE``,
  18. - ``AXES_LOCKOUT_URL``,
  19. - ``AXES_COOLOFF_MESSAGE``, and
  20. - ``AXES_PERMALOCK_MESSAGE``.
  21. """
  22. def __init__(self, get_response: Callable):
  23. self.get_response = get_response
  24. def __call__(self, request):
  25. response = self.get_response(request)
  26. if settings.AXES_ENABLED:
  27. if getattr(request, "axes_locked_out", None):
  28. response = get_lockout_response(request) # type: ignore
  29. return response