expephalon/core/mixins/auth.py

36 lines
1.6 KiB
Python
Raw Normal View History

2020-05-21 12:54:59 +00:00
from django.contrib.auth.mixins import AccessMixin
from django.contrib.messages import error
from django.views.decorators.cache import never_cache
2020-06-03 15:05:18 +00:00
from django.contrib.auth.views import redirect_to_login
2020-05-21 12:54:59 +00:00
from core.models.profiles import AdminProfile
2020-06-03 15:05:18 +00:00
from core.exceptions.auth import InsufficientPermissionsException
2020-05-21 12:54:59 +00:00
class AdminMixin(AccessMixin):
2020-06-03 15:05:18 +00:00
permissions = []
@never_cache
2020-05-21 12:54:59 +00:00
def dispatch(self, request, *args, **kwargs):
if not request.user.is_authenticated:
self.permission_denied_message = "You must be logged in to access this area."
else:
try:
2020-06-03 15:05:18 +00:00
user_permissions = AdminProfile.objects.get(user=request.user).permissions
for permission in self.permissions:
if not permission in user_permissions:
raise InsufficientPermissionsException(f"Missing permission: {permission}")
2020-05-21 12:54:59 +00:00
return super().dispatch(request, *args, **kwargs)
except AdminProfile.DoesNotExist:
self.permission_denied_message = "You must be an administrator to access this area."
2020-06-03 15:05:18 +00:00
except InsufficientPermissionsException:
self.permission_denied_message = "You do not have the necessary permissions to access this page."
return self.handle_no_permission()
def handle_no_permission(self):
if self.raise_exception:
raise PermissionDenied(self.get_permission_denied_message())
2020-05-21 12:54:59 +00:00
2020-06-03 15:05:18 +00:00
error(self.request, self.permission_denied_message)
return redirect_to_login(self.request.get_full_path(), self.get_login_url(), self.get_redirect_field_name())