auth.py 1.8 KB

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