Poprawki stylu pokazywania przypisów.
[redakcja.git] / apps / django_cas / decorators.py
1 """Replacement authentication decorators that work around redirection loops"""
2
3 try:
4     from functools import wraps
5 except ImportError:
6     from django.utils.functional import wraps
7
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
12
13 __all__ = ['login_required', 'permission_required', 'user_passes_test']
14
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.
19     """
20
21     if not login_url:
22         from django.conf import settings
23         login_url = settings.LOGIN_URL
24
25     def decorator(view_func):
26         @wraps(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>')
32             else:
33                 path = '%s?%s=%s' % (login_url, redirect_field_name,
34                                      urlquote(request.get_full_path()))
35                 return HttpResponseRedirect(path)
36         return wrapper
37     return decorator
38
39
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.
43     """
44
45     return user_passes_test(lambda u: u.has_perm(perm), login_url=login_url)