| 1 |
"""View decorators. |
| 2 |
|
| 3 |
See also decorators provided by server-specific modules, such as |
| 4 |
:func:`django_downloadview.nginx.x_accel_redirect`. |
| 5 |
|
| 6 |
""" |
| 7 |
|
| 8 |
from functools import wraps |
| 9 |
|
| 10 |
from django.conf import settings |
| 11 |
from django.core.exceptions import PermissionDenied |
| 12 |
from django.core.signing import BadSignature, SignatureExpired, TimestampSigner |
| 13 |
|
| 14 |
|
| 15 |
class DownloadDecorator(object): |
| 16 |
"""View decorator factory to apply middleware to ``view_func``'s response. |
| 17 |
|
| 18 |
Middleware instance is built from ``middleware_factory`` with ``*args`` and |
| 19 |
``**kwargs``. Middleware factory is typically a class, such as some |
| 20 |
:py:class:`django_downloadview.BaseDownloadMiddleware` subclass. |
| 21 |
|
| 22 |
Response is built from view, then the middleware's ``process_response`` |
| 23 |
method is applied on response. |
| 24 |
|
| 25 |
""" |
| 26 |
|
| 27 |
def __init__(self, middleware_factory): |
| 28 |
"""Create a download view decorator.""" |
| 29 |
self.middleware_factory = middleware_factory |
| 30 |
|
| 31 |
def __call__(self, view_func, *middleware_args, **middleware_kwargs): |
| 32 |
"""Return ``view_func`` decorated with response middleware.""" |
| 33 |
|
| 34 |
def decorated(request, *view_args, **view_kwargs): |
| 35 |
"""Return view's response modified by middleware.""" |
| 36 |
response = view_func(request, *view_args, **view_kwargs) |
| 37 |
middleware = self.middleware_factory(*middleware_args, **middleware_kwargs) |
| 38 |
return middleware.process_response(request, response) |
| 39 |
|
| 40 |
return decorated |
| 41 |
|
| 42 |
|
| 43 |
def _signature_is_valid(request): |
| 44 |
""" |
| 45 |
Validator that raises a PermissionDenied error on invalid and |
| 46 |
mismatching signatures. |
| 47 |
""" |
| 48 |
|
| 49 |
signer = TimestampSigner() |
| 50 |
signature = request.GET.get("X-Signature") |
| 51 |
expiration = getattr(settings, "DOWNLOADVIEW_URL_EXPIRATION", None) |
| 52 |
|
| 53 |
try: |
| 54 |
signature_path = signer.unsign(signature, max_age=expiration) |
| 55 |
except SignatureExpired as e: |
| 56 |
raise PermissionDenied("Signature expired") from e |
| 57 |
except BadSignature as e: |
| 58 |
raise PermissionDenied("Signature invalid") from e |
| 59 |
except Exception as e: |
| 60 |
raise PermissionDenied("Signature error") from e |
| 61 |
|
| 62 |
if request.path != signature_path: |
| 63 |
raise PermissionDenied("Signature mismatch") |
| 64 |
|
| 65 |
|
| 66 |
def signature_required(function): |
| 67 |
""" |
| 68 |
Decorator that checks for X-Signature query parameter to authorize access to views. |
| 69 |
""" |
| 70 |
|
| 71 |
@wraps(function) |
| 72 |
def decorator(request, *args, **kwargs): |
| 73 |
_signature_is_valid(request) |
| 74 |
return function(request, *args, **kwargs) |
| 75 |
|
| 76 |
return decorator |