1 """Replacement authentication decorators that work around redirection loops"""
4 from functools import wraps
6 from django.utils.functional import wraps
8 from django.contrib.auth import REDIRECT_FIELD_NAME
9 from django.contrib.auth.decorators import login_required
10 from django.http import HttpResponseForbidden, HttpResponseRedirect
11 from django.utils.http import urlquote
13 __all__ = ['login_required', 'permission_required', 'user_passes_test']
15 def user_passes_test(test_func, login_url=None,
16 redirect_field_name=REDIRECT_FIELD_NAME):
17 """Replacement for django.contrib.auth.decorators.user_passes_test that
18 returns 403 Forbidden if the user is already logged in.
22 from django.conf import settings
23 login_url = settings.LOGIN_URL
25 def decorator(view_func):
27 def wrapper(request, *args, **kwargs):
28 if test_func(request.user):
29 return view_func(request, *args, **kwargs)
30 elif request.user.is_authenticated():
31 return HttpResponseForbidden('<h1>Permission denied</h1>')
33 path = '%s?%s=%s' % (login_url, redirect_field_name,
34 urlquote(request.get_full_path()))
35 return HttpResponseRedirect(path)
40 def permission_required(perm, login_url=None):
41 """Replacement for django.contrib.auth.decorators.permission_required that
42 returns 403 Forbidden if the user is already logged in.
45 return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)