This repository was archived by the owner on Sep 5, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathdecorators.py
More file actions
46 lines (40 loc) · 1.56 KB
/
decorators.py
File metadata and controls
46 lines (40 loc) · 1.56 KB
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
from functools import wraps
from django.http import HttpResponse
from django.shortcuts import redirect
def unauthenticated_user(view_func):
"""To avoid logging in/registering again if the user logged in"""
@wraps(view_func)
def wrapper_func(request, *args, **kwargs):
# Redirect to their profile if authenticated
if request.user.is_authenticated:
return redirect('earlydating-yourprofile')
# Else authenticate user
else:
return view_func(request, *args, **kwargs)
return wrapper_func
def allowed_users(allowed_roles=[]):
"""Restricting page access to specified user groups"""
def decorator(view_func):
@wraps(view_func)
def wrapper_func(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group in allowed_roles:
return view_func(request, *args, **kwargs)
else:
return HttpResponse('You are not authorized to view this page')
return wrapper_func
return decorator
def admin_only(view_func):
"""Restrict page access to only admins"""
@wraps(view_func)
def wrapper_function(request, *args, **kwargs):
group = None
if request.user.groups.exists():
group = request.user.groups.all()[0].name
if group == 'profile':
return redirect('earlydating-yourprofile')
if group == 'admin':
return view_func(request, *args, **kwargs)
return wrapper_function