Created
November 24, 2020 07:39
-
-
Save Andrew-Chen-Wang/bd30e31211ec8c1046886877e137cdf5 to your computer and use it in GitHub Desktop.
Django-ratelimit behind a reverse proxy without changing ip key
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
I've had to monkeypatch django-ratelimit due to slow development. | |
The patch is basically allowing Django Axes with Django ipware | |
to grab the IP address rather than taking the IP straight from | |
META attribute in the request object. | |
You can find an initial implementation here: | |
https://github.com/jsocol/django-ratelimit/pull/208 | |
but the PR lead no where due to just not knowing how | |
to properly give flexibility to devs. | |
""" | |
from django.apps import AppConfig | |
from django.utils.translation import gettext_lazy as _ | |
class AConfig(AppConfig): | |
def ready(self): | |
patch_rate_limit() | |
def patch_rate_limit(): | |
from axes.utils import get_client_ip_address | |
from ratelimit.core import _SIMPLE_KEYS, ip_mask | |
def user_or_ip(request): | |
if request.user.is_authenticated: | |
return str(request.user.pk) | |
return ip_mask(get_client_ip_address(request)) | |
_SIMPLE_KEYS["ip"] = lambda r: ip_mask(get_client_ip_address(r)) | |
_SIMPLE_KEYS["user_or_ip"] = user_or_ip |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment