auth.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. from django.conf import settings
  2. from django.contrib import auth
  3. from django.shortcuts import redirect
  4. from django.urls import NoReverseMatch
  5. from django.utils.http import is_safe_url
  6. from django.utils.six.moves.urllib.parse import urlparse
  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 = is_safe_url(
  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 = '{}?'.format(redirect_to_path)
  26. else:
  27. redirect_to_path = '{}&'.format(redirect_to_path)
  28. redirect_to_path = '{}ref=login'.format(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)