Skip to content

Commit

Permalink
add rate limiting to the urlcrypt view
Browse files Browse the repository at this point in the history
  • Loading branch information
dziegler committed Oct 30, 2010
1 parent ff87930 commit 228b310
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 11 deletions.
22 changes: 14 additions & 8 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,20 @@ Advanced lib usage::
Settings
********

``URLCRYPT_LOGIN_URL`` default: LOGIN_URL

If urlcrypt authentication fails, redirects to ``URLCRYPT_LOGIN_URL``.


``RUNNING_TESTS`` default: False

Set ``RUNNING_TESTS`` to True when running the urlcrypt tests.
- ``URLCRYPT_LOGIN_URL``

- default: ``LOGIN_URL``
- If urlcrypt authentication fails, redirects to ``URLCRYPT_LOGIN_URL``.

- ``URLCRYPT_RATE_LIMIT``

- default: ``60``
- The number of urlcrypt requests a unique visitor is allowed to make per minute.

- ``RUNNING_TESTS``

- default: ``False``
- Set ``RUNNING_TESTS`` to True when running the urlcrypt tests.

Credits
********
Expand Down
1 change: 1 addition & 0 deletions urlcrypt/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@

URLCRYPT_LOGIN_URL = getattr(settings, 'URLCRYPT_LOGIN_URL', settings.LOGIN_URL)
RUNNING_TESTS = getattr(settings, 'RUNNING_TESTS', False)
URLCRYPT_RATE_LIMIT = getattr(settings, 'URLCRYPT_RATE_LIMIT', 60)
25 changes: 22 additions & 3 deletions urlcrypt/views.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,30 @@
from django.contrib.auth import authenticate, login as auth_login
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect, HttpResponse
from django.core.cache import cache
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseForbidden

from urlcrypt import lib as urlcrypt
from urlcrypt.conf import URLCRYPT_LOGIN_URL
from urlcrypt.conf import URLCRYPT_LOGIN_URL, URLCRYPT_RATE_LIMIT

#@rate_limit(num=30)
def rate_limit(num=60):
"""
Limits the number of requests made by a unique visitor to this view to num per minute.
"""
def decorator(func):
def wrapper(request, *args, **kwargs):
cache_key = 'rate_limit.%s' % request.session._session_key
added = cache.add(cache_key, 1, timeout=60)
if added:
num_tries = 1
else:
num_tries = cache.incr(cache_key, delta=1)
if num_tries > num:
raise HttpResponseForbidden("Rate Limit Exceeded")
return func(request, *args, **kwargs)
return wrapper
return decorator

@rate_limit(num=URLCRYPT_RATE_LIMIT)
def login_redirect(request, token):
try:
decoded_data = urlcrypt.decode_login_token(token)
Expand Down

0 comments on commit 228b310

Please sign in to comment.