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