| 1 |
from functools import wraps |
| 2 |
|
| 3 |
from asgiref.sync import iscoroutinefunction |
| 4 |
|
| 5 |
|
| 6 |
def xframe_options_deny(view_func): |
| 7 |
""" |
| 8 |
Modify a view function so its response has the X-Frame-Options HTTP |
| 9 |
header set to 'DENY' as long as the response doesn't already have that |
| 10 |
header set. Usage: |
| 11 |
|
| 12 |
@xframe_options_deny |
| 13 |
def some_view(request): |
| 14 |
... |
| 15 |
""" |
| 16 |
|
| 17 |
if iscoroutinefunction(view_func): |
| 18 |
|
| 19 |
async def _view_wrapper(*args, **kwargs): |
| 20 |
response = await view_func(*args, **kwargs) |
| 21 |
if response.get("X-Frame-Options") is None: |
| 22 |
response["X-Frame-Options"] = "DENY" |
| 23 |
return response |
| 24 |
|
| 25 |
else: |
| 26 |
|
| 27 |
def _view_wrapper(*args, **kwargs): |
| 28 |
response = view_func(*args, **kwargs) |
| 29 |
if response.get("X-Frame-Options") is None: |
| 30 |
response["X-Frame-Options"] = "DENY" |
| 31 |
return response |
| 32 |
|
| 33 |
return wraps(view_func)(_view_wrapper) |
| 34 |
|
| 35 |
|
| 36 |
def xframe_options_sameorigin(view_func): |
| 37 |
""" |
| 38 |
Modify a view function so its response has the X-Frame-Options HTTP |
| 39 |
header set to 'SAMEORIGIN' as long as the response doesn't already have |
| 40 |
that header set. Usage: |
| 41 |
|
| 42 |
@xframe_options_sameorigin |
| 43 |
def some_view(request): |
| 44 |
... |
| 45 |
""" |
| 46 |
|
| 47 |
if iscoroutinefunction(view_func): |
| 48 |
|
| 49 |
async def _view_wrapper(*args, **kwargs): |
| 50 |
response = await view_func(*args, **kwargs) |
| 51 |
if response.get("X-Frame-Options") is None: |
| 52 |
response["X-Frame-Options"] = "SAMEORIGIN" |
| 53 |
return response |
| 54 |
|
| 55 |
else: |
| 56 |
|
| 57 |
def _view_wrapper(*args, **kwargs): |
| 58 |
response = view_func(*args, **kwargs) |
| 59 |
if response.get("X-Frame-Options") is None: |
| 60 |
response["X-Frame-Options"] = "SAMEORIGIN" |
| 61 |
return response |
| 62 |
|
| 63 |
return wraps(view_func)(_view_wrapper) |
| 64 |
|
| 65 |
|
| 66 |
def xframe_options_exempt(view_func): |
| 67 |
""" |
| 68 |
Modify a view function by setting a response variable that instructs |
| 69 |
XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. Usage: |
| 70 |
|
| 71 |
@xframe_options_exempt |
| 72 |
def some_view(request): |
| 73 |
... |
| 74 |
""" |
| 75 |
|
| 76 |
if iscoroutinefunction(view_func): |
| 77 |
|
| 78 |
async def _view_wrapper(*args, **kwargs): |
| 79 |
response = await view_func(*args, **kwargs) |
| 80 |
response.xframe_options_exempt = True |
| 81 |
return response |
| 82 |
|
| 83 |
else: |
| 84 |
|
| 85 |
def _view_wrapper(*args, **kwargs): |
| 86 |
response = view_func(*args, **kwargs) |
| 87 |
response.xframe_options_exempt = True |
| 88 |
return response |
| 89 |
|
| 90 |
return wraps(view_func)(_view_wrapper) |