2022-11-05 20:17:27 +00:00
|
|
|
from functools import wraps
|
|
|
|
|
2022-11-17 04:14:05 +00:00
|
|
|
from django.contrib.auth.decorators import user_passes_test
|
2022-11-05 20:17:27 +00:00
|
|
|
from django.contrib.auth.views import redirect_to_login
|
|
|
|
from django.http import HttpResponseRedirect
|
|
|
|
|
|
|
|
|
|
|
|
def identity_required(function):
|
|
|
|
"""
|
|
|
|
Decorator for views that ensures an active identity is selected.
|
|
|
|
"""
|
|
|
|
|
|
|
|
@wraps(function)
|
|
|
|
def inner(request, *args, **kwargs):
|
|
|
|
# They do have to be logged in
|
|
|
|
if not request.user.is_authenticated:
|
|
|
|
return redirect_to_login(next=request.get_full_path())
|
|
|
|
# If there's no active one, try to auto-select one
|
2022-11-06 20:48:04 +00:00
|
|
|
if request.identity is None:
|
2022-11-05 20:17:27 +00:00
|
|
|
possible_identities = list(request.user.identities.all())
|
|
|
|
if len(possible_identities) != 1:
|
|
|
|
# OK, send them to the identity selection page to select/create one
|
|
|
|
return HttpResponseRedirect("/identity/select/")
|
|
|
|
identity = possible_identities[0]
|
2022-11-06 20:48:04 +00:00
|
|
|
request.session["identity_id"] = identity.pk
|
|
|
|
request.identity = identity
|
2022-11-05 20:17:27 +00:00
|
|
|
return function(request, *args, **kwargs)
|
|
|
|
|
|
|
|
return inner
|
2022-11-17 04:14:05 +00:00
|
|
|
|
|
|
|
|
2022-12-20 09:01:54 +00:00
|
|
|
def moderator_required(function):
|
|
|
|
return user_passes_test(
|
|
|
|
lambda user: user.is_authenticated and (user.admin or user.moderator)
|
|
|
|
)(function)
|
|
|
|
|
|
|
|
|
2022-11-17 04:14:05 +00:00
|
|
|
def admin_required(function):
|
2022-11-26 01:37:09 +00:00
|
|
|
return user_passes_test(lambda user: user.is_authenticated and user.admin)(function)
|