utils.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. """
  2. Axes utility functions that are publicly available.
  3. This module is separate for historical reasons
  4. and offers a backwards compatible import path.
  5. """
  6. from logging import getLogger
  7. from typing import Optional
  8. from django.http import HttpRequest
  9. from axes.conf import settings
  10. from axes.handlers.proxy import AxesProxyHandler
  11. from axes.helpers import get_client_ip_address
  12. log = getLogger(__name__)
  13. def reset(ip: str = None, username: str = None, ip_or_username=False) -> int:
  14. """
  15. Reset records that match IP or username, and return the count of removed attempts.
  16. This utility method is meant to be used from the CLI or via Python API.
  17. """
  18. return AxesProxyHandler.reset_attempts(
  19. ip_address=ip, username=username, ip_or_username=ip_or_username
  20. )
  21. def reset_request(request: HttpRequest) -> int:
  22. """
  23. Reset records that match IP or username, and return the count of removed attempts.
  24. This utility method is meant to be used from the CLI or via Python API.
  25. """
  26. ip: Optional[str] = get_client_ip_address(request)
  27. username = request.GET.get("username", None)
  28. ip_or_username = settings.AXES_LOCK_OUT_BY_USER_OR_IP
  29. if settings.AXES_ONLY_USER_FAILURES:
  30. ip = None
  31. elif not (
  32. settings.AXES_LOCK_OUT_BY_USER_OR_IP
  33. or settings.AXES_LOCK_OUT_BY_COMBINATION_USER_AND_IP
  34. ):
  35. username = None
  36. if not ip and not username:
  37. return 0
  38. # We don't want to reset everything, if there is some wrong request parameter
  39. # if settings.AXES_USE_USER_AGENT:
  40. # TODO: reset based on user_agent?
  41. return reset(ip, username, ip_or_username)