説明なし

decorators.py 1.2KB

123456789101112131415161718192021222324252627282930
  1. from functools import wraps
  2. from django.http import HttpResponseRedirect
  3. from django.contrib.auth.decorators import user_passes_test
  4. from django.conf import settings
  5. superuser_required = user_passes_test(lambda u: u.is_superuser, login_url=settings.LOGIN_URL)
  6. def https_required(view):
  7. """A view decorator that redirects to HTTPS if this view is requested
  8. over HTTP. Allows HTTP when DEBUG is on and during unit tests.
  9. """
  10. @wraps(view)
  11. def view_or_redirect(request, *args, **kwargs):
  12. if not request.is_secure():
  13. # Just load the view on a devserver or in the testing environment.
  14. if settings.DEBUG or request.META['SERVER_NAME'] == "testserver":
  15. return view(request, *args, **kwargs)
  16. else:
  17. # Redirect to HTTPS.
  18. request_url = request.build_absolute_uri(request.get_full_path())
  19. secure_url = request_url.replace('http://', 'https://')
  20. return HttpResponseRedirect(secure_url)
  21. else:
  22. # It's HTTPS, so load the view.
  23. return view(request, *args, **kwargs)
  24. return view_or_redirect
  25. def https_and_superuser_required(view):
  26. return https_required(superuser_required(view))