from django.contrib.auth.mixins import AccessMixin from django.contrib.messages import error from django.views.decorators.cache import never_cache from django.contrib.auth.views import redirect_to_login from core.models.profiles import AdminProfile from core.exceptions.auth import InsufficientPermissionsException class AdminMixin(AccessMixin): permissions = [] @never_cache 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: 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}") return super().dispatch(request, *args, **kwargs) except AdminProfile.DoesNotExist: self.permission_denied_message = "You must be an administrator to access this area." 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()) 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())