| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from django.conf import settings |
| 4 |
from django.http import HttpRequest, HttpResponse |
| 5 |
|
| 6 |
from allauth import app_settings |
| 7 |
from allauth.core.exceptions import RateLimited # noqa |
| 8 |
from allauth.core.internal import ratelimit as _impl |
| 9 |
from allauth.core.internal.ratelimit import Rate # noqa |
| 10 |
from allauth.utils import import_callable |
| 11 |
|
| 12 |
|
| 13 |
def clear(request: HttpRequest, *, action: str, key=None, user=None) -> None: |
| 14 |
from allauth.account import app_settings |
| 15 |
|
| 16 |
_impl.clear( |
| 17 |
request=request, |
| 18 |
config=app_settings.RATE_LIMITS, |
| 19 |
action=action, |
| 20 |
key=key, |
| 21 |
user=user, |
| 22 |
) |
| 23 |
|
| 24 |
|
| 25 |
def consume( |
| 26 |
request: HttpRequest, |
| 27 |
*, |
| 28 |
action, |
| 29 |
key=None, |
| 30 |
user=None, |
| 31 |
dry_run: bool = False, |
| 32 |
raise_exception: bool = False, |
| 33 |
) -> bool: |
| 34 |
""" |
| 35 |
TODO: We ened to deprecate this module and keep rate limiting internal |
| 36 |
to allauth. This method is using `allauth.account.app_settings` as a |
| 37 |
hard-coded source of settings, which is bad for reusability elsewhere. |
| 38 |
""" |
| 39 |
from allauth.account import app_settings |
| 40 |
|
| 41 |
usage = _impl.consume( |
| 42 |
request=request, |
| 43 |
config=app_settings.RATE_LIMITS, |
| 44 |
action=action, |
| 45 |
key=key, |
| 46 |
user=user, |
| 47 |
dry_run=dry_run, |
| 48 |
raise_exception=raise_exception, |
| 49 |
) |
| 50 |
if not usage: |
| 51 |
return False |
| 52 |
return True |
| 53 |
|
| 54 |
|
| 55 |
def respond_429(request: HttpRequest) -> HttpResponse: |
| 56 |
if app_settings.HEADLESS_ENABLED and hasattr( |
| 57 |
request.allauth, "headless" # type:ignore[attr-defined] |
| 58 |
): |
| 59 |
from allauth.headless.base.response import RateLimitResponse |
| 60 |
|
| 61 |
return RateLimitResponse(request) |
| 62 |
|
| 63 |
try: |
| 64 |
handler429 = import_callable(f"{settings.ROOT_URLCONF}.handler429") |
| 65 |
handler429 = import_callable(handler429) |
| 66 |
except (ImportError, AttributeError): |
| 67 |
handler429 = _impl.handler429 |
| 68 |
return handler429(request) |
| 69 |
|
| 70 |
|
| 71 |
def consume_or_429(request: HttpRequest, *args, **kwargs) -> HttpResponse | None: |
| 72 |
if not consume(request, *args, **kwargs): |
| 73 |
return respond_429(request) |
| 74 |
return None |