csrf.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from functools import wraps
  2. from django.middleware.csrf import CsrfViewMiddleware, get_token
  3. from django.utils.decorators import decorator_from_middleware
  4. csrf_protect = decorator_from_middleware(CsrfViewMiddleware)
  5. csrf_protect.__name__ = "csrf_protect"
  6. csrf_protect.__doc__ = """
  7. This decorator adds CSRF protection in exactly the same way as
  8. CsrfViewMiddleware, but it can be used on a per view basis. Using both, or
  9. using the decorator multiple times, is harmless and efficient.
  10. """
  11. class _EnsureCsrfToken(CsrfViewMiddleware):
  12. # Behave like CsrfViewMiddleware but don't reject requests or log warnings.
  13. def _reject(self, request, reason):
  14. return None
  15. requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken)
  16. requires_csrf_token.__name__ = "requires_csrf_token"
  17. requires_csrf_token.__doc__ = """
  18. Use this decorator on views that need a correct csrf_token available to
  19. RequestContext, but without the CSRF protection that csrf_protect
  20. enforces.
  21. """
  22. class _EnsureCsrfCookie(CsrfViewMiddleware):
  23. def _reject(self, request, reason):
  24. return None
  25. def process_view(self, request, callback, callback_args, callback_kwargs):
  26. retval = super().process_view(request, callback, callback_args, callback_kwargs)
  27. # Force process_response to send the cookie
  28. get_token(request)
  29. return retval
  30. ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie)
  31. ensure_csrf_cookie.__name__ = "ensure_csrf_cookie"
  32. ensure_csrf_cookie.__doc__ = """
  33. Use this decorator to ensure that a view sets a CSRF cookie, whether or not it
  34. uses the csrf_token template tag, or the CsrfViewMiddleware is used.
  35. """
  36. def csrf_exempt(view_func):
  37. """Mark a view function as being exempt from the CSRF view protection."""
  38. # view_func.csrf_exempt = True would also work, but decorators are nicer
  39. # if they don't have side effects, so return a new function.
  40. @wraps(view_func)
  41. def wrapper_view(*args, **kwargs):
  42. return view_func(*args, **kwargs)
  43. wrapper_view.csrf_exempt = True
  44. return wrapper_view