forked from harikishan81001/custom_decorator
/
custom_decorators.py
86 lines (73 loc) · 2.72 KB
/
custom_decorators.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
__author__ = 'hari'
from django.core.exceptions import PermissionDenied
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.decorators import permission_required
from exceptions import Exception
class NotValidCheck(Exception):
pass
ALLOWED_CHECK = ['OR', 'AND', 'NOT']
def permission_set_required(
perm, perm_check='OR',
login_url=None, raise_exception=False):
"""
decorator for the views that check whether a user has
a particular set of permissions based on perm_check like
1 - if perm_check == 'OR'
User must have a single permission from the set of permission
2 - if perm_check == 'AND'
User must have all permissions from the set to pass decorator
3 - if perm_check == 'NOT'
then user must not have mentioned permission
if raise_exception is given then PermissionDenied exception will be
raised.
"""
def check_perms(user):
if perm_check not in ALLOWED_CHECK:
raise NotValidCheck(
'perm_check is not valid expected is "AND", '
' "OR", "NOT" but found %s' % perm_check)
if not perm_check == 'NOT':
if not isinstance(perm, list):
return permission_required(
perm, login_url=login_url,
raise_exception=raise_exception)
else:
if perm_check == 'OR':
return check_or_perms(user, perm)
elif perm_check == 'AND':
return check_and_perms(user, perm)
else:
return check_not_perms(user, perm)
def check_not_perms(user, perm):
flag = True
if not isinstance(perm, list):
if user.has_perm(perm):
flag = False
else:
for each in perm:
if user.has_perm(each):
flag = False
else:
flag = True
return flag
def check_or_perms(user, perm_list):
flag = False
for each in perm_list:
if user.has_perm(each):
flag = True
#In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
return flag
def check_and_perms(user, perm_list):
flag = False
for each in perm_list:
if user.has_perm(each):
flag = True
else:
flag = False
#In case the 403 handler should be called raise the exception
if raise_exception:
raise PermissionDenied
return flag
return user_passes_test(check_perms, login_url=login_url)