auth.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from urllib.parse import urlparse
  2. from django.conf import settings
  3. from django.contrib import auth
  4. from django.shortcuts import redirect
  5. from django.urls import NoReverseMatch
  6. from django.utils.http import url_has_allowed_host_and_scheme
  7. from django.views.decorators.cache import never_cache
  8. from django.views.decorators.csrf import csrf_protect
  9. from django.views.decorators.debug import sensitive_post_parameters
  10. @sensitive_post_parameters()
  11. @never_cache
  12. @csrf_protect
  13. def login(request):
  14. if request.method == "POST":
  15. redirect_to = request.POST.get("redirect_to")
  16. if redirect_to:
  17. is_redirect_safe = url_has_allowed_host_and_scheme(
  18. url=redirect_to,
  19. allowed_hosts={request.get_host()},
  20. require_https=request.is_secure(),
  21. )
  22. if is_redirect_safe:
  23. redirect_to_path = urlparse(redirect_to).path
  24. if "?" not in redirect_to_path:
  25. redirect_to_path = "%s?" % redirect_to_path
  26. else:
  27. redirect_to_path = "%s&" % redirect_to_path
  28. redirect_to_path = "%sref=login" % redirect_to_path
  29. try:
  30. return redirect(redirect_to_path)
  31. except NoReverseMatch:
  32. pass
  33. return redirect(settings.LOGIN_REDIRECT_URL)
  34. @never_cache
  35. @csrf_protect
  36. def logout(request):
  37. if request.method == "POST" and request.user.is_authenticated:
  38. auth.logout(request)
  39. return redirect(settings.LOGIN_REDIRECT_URL)