54 lines
No EOL
1.9 KiB
Python
54 lines
No EOL
1.9 KiB
Python
from django.utils.decorators import method_decorator
|
|
from django.shortcuts import redirect
|
|
from django.contrib import messages
|
|
from django.contrib.auth import REDIRECT_FIELD_NAME
|
|
from django.contrib.auth.decorators import login_required
|
|
from django.contrib.auth.views import redirect_to_login, RedirectURLMixin as SuccessURLAllowedHostsMixin
|
|
from django.conf import settings
|
|
from django.contrib.auth.mixins import UserPassesTestMixin
|
|
from django.urls import reverse_lazy
|
|
from django.utils.http import url_has_allowed_host_and_scheme
|
|
|
|
class SuperUserRequiredMixin(UserPassesTestMixin):
|
|
def test_func(self):
|
|
try:
|
|
return self.request.user.is_superuser
|
|
except:
|
|
return False
|
|
|
|
def get_login_url(self):
|
|
return reverse_lazy("localauth:login")
|
|
|
|
class LoginRequiredMixin(UserPassesTestMixin):
|
|
def test_func(self):
|
|
try:
|
|
return self.request.user.is_authenticated
|
|
except:
|
|
return False
|
|
|
|
def get_login_url(self):
|
|
return reverse_lazy("localauth:login")
|
|
|
|
class MultiPermissionMixin:
|
|
MIXINS = []
|
|
|
|
def dispatch(self, request, *args, **kwargs):
|
|
for mixin in self.MIXINS:
|
|
if not mixin.test_func(self):
|
|
return redirect_to_login(request.get_full_path(), mixin.get_login_url(self), REDIRECT_FIELD_NAME)
|
|
|
|
return super().dispatch(request, *args, **kwargs)
|
|
|
|
class RedirectToNextMixin(SuccessURLAllowedHostsMixin):
|
|
def get_redirect_url(self):
|
|
"""Return the user-originating redirect URL if it's safe."""
|
|
redirect_to = self.request.POST.get(
|
|
REDIRECT_FIELD_NAME,
|
|
self.request.GET.get(REDIRECT_FIELD_NAME, '')
|
|
)
|
|
url_is_safe = url_has_allowed_host_and_scheme(
|
|
url=redirect_to,
|
|
allowed_hosts=self.get_success_url_allowed_hosts(),
|
|
require_https=self.request.is_secure(),
|
|
)
|
|
return redirect_to if url_is_safe else '' |