1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55 | ### Decorator to logout the admin from the regular pages
try:
from functools import update_wrapper, wraps
except ImportError:
from django.utils.functional import update_wrapper, wraps # Python 2.4 fallback.
from django.http import HttpResponseRedirect
from django.utils.decorators import available_attrs
from django.utils.http import urlquote
def logout_user_and_redirect_on_test(test_func, redirect_url = None ):
"""
Decorator for views that checks that the user passes the given test,
redirecting to the log-in page if necessary. The test should be a callable
that takes the user object and returns True if the user passes.
"""
def decorator(view_func):
def _wrapped_view(request, *args, **kwargs):
if test_func(request.user):
return view_func(request, *args, **kwargs)
from django.contrib.auth import logout
logout(request)
if redirect_url:
return HttpResponseRedirect(redirect_url)
else :
return HttpResponseRedirect(request.path)
return wraps(view_func, assigned=available_attrs(view_func))(_wrapped_view)
return decorator
#---------------------------
def logout_admin(user):
if user.is_authenticated and (user.is_staff or user.is_superuser):
return False
else :
return True
def logout_non_xxxxxx(user):
try :
if user.is_authenticated and user.xxxx_related.xxxr:
return False
else :
return True
except :
return False
############# sample view
@logout_user_and_redirect_on_test(logout_non_xxxxxx,'/')
@logout_user_and_redirect_on_test(logout_admin)
def some_view(request):
return HttpResponse('Hello World')
|
Comments