Skip to content

Commit 99a14b3

Browse files
committed
Move the decoraters + utilities to new ietfauth/utils.py file
- Legacy-Id: 5210
1 parent 8f6a26b commit 99a14b3

2 files changed

Lines changed: 119 additions & 84 deletions

File tree

ietf/ietfauth/decorators.py

Lines changed: 3 additions & 84 deletions
Original file line numberDiff line numberDiff line change
@@ -30,87 +30,6 @@
3030
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
3131
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
3232

33-
from django.utils.http import urlquote
34-
from django.conf import settings
35-
from django.db.models import Q
36-
from django.http import HttpResponseRedirect, HttpResponseForbidden
37-
from django.contrib.auth import REDIRECT_FIELD_NAME
38-
39-
def passes_test_decorator(test_func, message):
40-
"""
41-
Decorator creator that creates a decorator for checking that user
42-
passes the test, redirecting to login or returning a 403
43-
error. The test function should be on the form fn(user) ->
44-
true/false.
45-
"""
46-
def decorate(view_func):
47-
def inner(request, *args, **kwargs):
48-
if not request.user.is_authenticated():
49-
return HttpResponseRedirect('%s?%s=%s' % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path())))
50-
elif test_func(request.user):
51-
return view_func(request, *args, **kwargs)
52-
else:
53-
return HttpResponseForbidden(message)
54-
return inner
55-
return decorate
56-
57-
def group_required(*group_names):
58-
"""Decorator for views that checks that the user is logged in,
59-
and belongs to (at least) one of the listed groups."""
60-
return passes_test_decorator(lambda u: u.groups.filter(name__in=group_names),
61-
"Restricted to group%s %s" % ("s" if len(group_names) != 1 else "", ",".join(group_names)))
62-
63-
64-
def has_role(user, role_names):
65-
"""Determines whether user has any of the given standard roles
66-
given. Role names must be a list or, in case of a single value, a
67-
string."""
68-
if isinstance(role_names, str) or isinstance(role_names, unicode):
69-
role_names = [ role_names ]
70-
71-
if not user or not user.is_authenticated():
72-
return False
73-
74-
if not hasattr(user, "roles_check_cache"):
75-
user.roles_check_cache = {}
76-
77-
key = frozenset(role_names)
78-
if key not in user.roles_check_cache:
79-
80-
from ietf.person.models import Person
81-
from ietf.group.models import Role
82-
83-
try:
84-
person = user.get_profile()
85-
except Person.DoesNotExist:
86-
return False
87-
88-
role_qs = {
89-
"Area Director": Q(person=person, name__in=("pre-ad", "ad"), group__type="area", group__state="active"),
90-
"Secretariat": Q(person=person, name="secr", group__acronym="secretariat"),
91-
"IANA": Q(person=person, name="auth", group__acronym="iana"),
92-
"RFC Editor": Q(person=person, name="auth", group__acronym="rfceditor"),
93-
"IAD": Q(person=person, name="admdir", group__acronym="ietf"),
94-
"IETF Chair": Q(person=person, name="chair", group__acronym="ietf"),
95-
"IAB Chair": Q(person=person, name="chair", group__acronym="iab"),
96-
"WG Chair": Q(person=person,name="chair", group__type="wg", group__state="active"),
97-
"WG Secretary": Q(person=person,name="secr", group__type="wg", group__state="active"),
98-
}
99-
100-
filter_expr = Q()
101-
for r in role_names:
102-
filter_expr |= role_qs[r]
103-
104-
user.roles_check_cache[key] = bool(Role.objects.filter(filter_expr)[:1])
105-
106-
return user.roles_check_cache[key]
107-
108-
def role_required(*role_names):
109-
"""View decorator for checking that the user is logged in and
110-
has one of the listed roles."""
111-
return passes_test_decorator(lambda u: has_role(u, role_names),
112-
"Restricted to role%s %s" % ("s" if len(role_names) != 1 else "", ", ".join(role_names)))
113-
114-
if settings.USE_DB_REDESIGN_PROXY_CLASSES:
115-
# overwrite group_required
116-
group_required = lambda *group_names: role_required(*[n.replace("Area_Director", "Area Director") for n in group_names])
33+
# REDESIGN: backwards compatibility, to be deleted
34+
from ietf.ietfauth.utils import role_required, has_role, passes_test_decorator
35+
group_required = lambda *group_names: role_required(*[n.replace("Area_Director", "Area Director") for n in group_names])

ietf/ietfauth/utils.py

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
# various authentication and authorization utilities
2+
3+
from django.utils.http import urlquote
4+
from django.conf import settings
5+
from django.db.models import Q
6+
from django.http import HttpResponseRedirect, HttpResponseForbidden
7+
from django.contrib.auth import REDIRECT_FIELD_NAME
8+
9+
from ietf.doc.models import Document
10+
from ietf.person.models import Person
11+
from ietf.group.models import Role
12+
13+
def user_is_person(user, person):
14+
"""Test whether user is associated with person."""
15+
if not user.is_authenticated() or not person:
16+
return False
17+
18+
if person.user_id == None:
19+
return False
20+
21+
return person.user_id == user.id
22+
23+
def has_role(user, role_names):
24+
"""Determines whether user has any of the given standard roles
25+
given. Role names must be a list or, in case of a single value, a
26+
string."""
27+
if isinstance(role_names, str) or isinstance(role_names, unicode):
28+
role_names = [ role_names ]
29+
30+
if not user or not user.is_authenticated():
31+
return False
32+
33+
# use cache to avoid checking the same permissions again and again
34+
if not hasattr(user, "roles_check_cache"):
35+
user.roles_check_cache = {}
36+
37+
key = frozenset(role_names)
38+
if key not in user.roles_check_cache:
39+
try:
40+
person = user.get_profile()
41+
except Person.DoesNotExist:
42+
return False
43+
44+
role_qs = {
45+
"Area Director": Q(person=person, name__in=("pre-ad", "ad"), group__type="area", group__state="active"),
46+
"Secretariat": Q(person=person, name="secr", group__acronym="secretariat"),
47+
"IANA": Q(person=person, name="auth", group__acronym="iana"),
48+
"RFC Editor": Q(person=person, name="auth", group__acronym="rfceditor"),
49+
"IAD": Q(person=person, name="admdir", group__acronym="ietf"),
50+
"IETF Chair": Q(person=person, name="chair", group__acronym="ietf"),
51+
"IAB Chair": Q(person=person, name="chair", group__acronym="iab"),
52+
"WG Chair": Q(person=person,name="chair", group__type="wg", group__state="active"),
53+
"WG Secretary": Q(person=person,name="secr", group__type="wg", group__state="active"),
54+
}
55+
56+
filter_expr = Q()
57+
for r in role_names:
58+
filter_expr |= role_qs[r]
59+
60+
user.roles_check_cache[key] = bool(Role.objects.filter(filter_expr)[:1])
61+
62+
return user.roles_check_cache[key]
63+
64+
65+
# convenient decorator
66+
67+
def passes_test_decorator(test_func, message):
68+
"""Decorator creator that creates a decorator for checking that
69+
user passes the test, redirecting to login or returning a 403
70+
error. The test function should be on the form fn(user) ->
71+
true/false."""
72+
def decorate(view_func):
73+
def inner(request, *args, **kwargs):
74+
if not request.user.is_authenticated():
75+
return HttpResponseRedirect('%s?%s=%s' % (settings.LOGIN_URL, REDIRECT_FIELD_NAME, urlquote(request.get_full_path())))
76+
elif test_func(request.user):
77+
return view_func(request, *args, **kwargs)
78+
else:
79+
return HttpResponseForbidden(message)
80+
return inner
81+
return decorate
82+
83+
def role_required(*role_names):
84+
"""View decorator for checking that the user is logged in and
85+
has one of the listed roles."""
86+
return passes_test_decorator(lambda u: has_role(u, role_names),
87+
"Restricted to role%s %s" % ("s" if len(role_names) != 1 else "", ", ".join(role_names)))
88+
89+
# specific permissions
90+
91+
def is_authorized_in_doc_stream(user, doc):
92+
"""Return whether user is authorized to perform stream duties on
93+
document."""
94+
if has_role(user, ["Secretariat"]):
95+
return True
96+
97+
if not doc.stream or not user.is_authenticated():
98+
return False
99+
100+
# must be authorized in the stream or group
101+
102+
group_req = None
103+
104+
if doc.stream.slug == "ietf":
105+
if not doc.group.type == "individ":
106+
group_req = Q(group=doc.group)
107+
elif doc.stream.slug == "irtf":
108+
group_req = Q(group__acronym=doc.stream.slug) | Q(group=doc.group)
109+
elif doc.stream.slug in ("iab", "ise"):
110+
group_req = Q(group__acronym=doc.stream.slug)
111+
112+
if not group_req:
113+
return False
114+
115+
return bool(Role.objects.filter(Q(name__in=("chair", "delegate", "auth"), person__user=user) & group_req))
116+

0 commit comments

Comments
 (0)