3
0
Fork 0
mirror of https://github.com/nanoy42/coope synced 2024-11-25 04:43:11 +00:00
coope/coopeV3/acl.py

80 lines
2.4 KiB
Python
Raw Normal View History

2018-11-22 21:52:24 +00:00
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import User
from django.shortcuts import redirect, get_object_or_404
from django.urls import reverse
2019-02-28 12:18:41 +00:00
from functools import wraps
2018-11-22 21:52:24 +00:00
from preferences.models import GeneralPreferences
def admin_required(view):
"""
2019-02-28 12:18:41 +00:00
Test if the user is staff.
2018-11-22 21:52:24 +00:00
"""
2018-11-25 23:15:09 +00:00
return user_passes_test(lambda u: u.is_staff)(view)
2018-11-22 21:52:24 +00:00
def superuser_required(view):
"""
2019-02-28 12:18:41 +00:00
Test if the user is superuser.
2018-11-22 21:52:24 +00:00
"""
2018-11-25 23:15:09 +00:00
return user_passes_test(lambda u: u.is_superuser)(view)
2018-11-22 21:52:24 +00:00
def self_or_has_perm(pkName, perm):
"""
2019-02-28 12:18:41 +00:00
Test if the user is the request user (pk) or has perm permission.
2018-11-22 21:52:24 +00:00
"""
def decorator(view):
2019-02-28 12:18:41 +00:00
@wraps(view)
2018-11-22 21:52:24 +00:00
def wrapper(request, *args, **kwargs):
user = get_object_or_404(User, pk=kwargs[pkName])
if(user == request.user or request.user.has_perm(perm)):
return view(request, *args, **kwargs)
else:
return redirect(reverse('users:login'))
return wrapper
return decorator
def active_required(view):
2019-02-28 12:18:41 +00:00
"""
Test if the site is active (:attr:`preferences.models.GeneralPreferences.is_active`).
"""
@wraps(view)
2018-11-22 21:52:24 +00:00
def wrapper(request, *args, **kwargs):
gp,_ = GeneralPreferences.objects.get_or_create(pk=1)
if(not gp.is_active):
2018-12-14 08:17:56 +00:00
return redirect(reverse('preferences:inactive'))
2018-11-22 21:52:24 +00:00
return view(request, *args, **kwargs)
return wrapper
def acl_or(*perms):
2019-02-28 12:18:41 +00:00
"""
Test if a user has one of perms
"""
2018-11-22 21:52:24 +00:00
def decorator(view):
2019-02-28 12:18:41 +00:00
@wraps(view)
2018-11-22 21:52:24 +00:00
def wrapper(request,*args, **kwargs):
can_pass = request.user.has_perm(perms[0])
for perm in perms:
can_pass = can_pass or request.user.has_perm(perm)
if can_pass:
return view(request, *args, **kwargs)
else:
return redirect(reverse('users:login'))
return wrapper
return decorator
def acl_and(*perms):
2019-02-28 12:18:41 +00:00
"""
Test if a user has all perms
"""
2018-11-22 21:52:24 +00:00
def decorator(view):
2019-02-28 12:18:41 +00:00
@wraps(view)
2018-11-22 21:52:24 +00:00
def wrapper(request,*args, **kwargs):
can_pass = request.user.has_perm(perms[0])
for perm in perms:
can_pass = can_pass and request.user.has_perm(perm)
if can_pass:
return view(request, *args, **kwargs)
else:
return redirect(reverse('users:login'))
return wrapper
return decorator