JourneyJoker/localauth/mixins.py

53 lines
1.8 KiB
Python
Raw Normal View History

2021-03-22 17:42:07 +00:00
from django.utils.decorators import method_decorator
from django.shortcuts import redirect
from django.contrib import messages
2021-05-26 16:42:22 +00:00
from django.contrib.auth import REDIRECT_FIELD_NAME
2021-03-22 17:42:07 +00:00
from django.contrib.auth.decorators import login_required
2021-05-26 16:42:22 +00:00
from django.contrib.auth.views import redirect_to_login, SuccessURLAllowedHostsMixin
2021-03-22 17:42:07 +00:00
from django.conf import settings
from django.contrib.auth.mixins import UserPassesTestMixin
from django.urls import reverse_lazy
2021-03-22 17:42:07 +00:00
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):
2021-05-26 16:42:22 +00:00
return redirect_to_login(request.get_full_path(), mixin.get_login_url(self), REDIRECT_FIELD_NAME)
2021-03-22 17:42:07 +00:00
return super().dispatch(request, *args, **kwargs)
2021-05-26 16:42:22 +00:00
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 ''