Created
June 2, 2021 14:21
-
-
Save LowerDeez/4e20655ad31ce84f0e4c3f841f705b77 to your computer and use it in GitHub Desktop.
Protected file access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.http import HttpResponse | |
from django.http import HttpResponseForbidden | |
from apps.order.models import Certificate, Order | |
__all__ = ( | |
'files_access', | |
) | |
def files_access(request, path): | |
""" | |
When trying to access : | |
myproject.com/media/uploads/passport.png | |
If access is authorized, the request will be redirected to | |
myproject.com/protected/media/uploads/passport.png | |
This special URL will be handle by nginx we the help of X-Accel | |
""" | |
obj = None | |
model = request.GET.get('model', '') | |
display_mode = request.GET.get('display_mode', 'attachment') | |
file = request.GET.get('file', 'pdf') | |
content_type = request.GET.get('content_type', 'application/pdf') | |
for_all = request.GET.get('for_all', False) | |
pk = path | |
access_granted = False | |
user = request.user | |
if user.is_authenticated: | |
if model == 'order': | |
obj = Order.objects.get(pk=pk) | |
elif model == 'certificate': | |
obj = Certificate.objects.get(pk=pk) | |
if user.is_superuser: | |
access_granted = True | |
elif user.is_dealer and obj.dealer == user.dealer: | |
access_granted = True | |
if for_all == 'True': | |
access_granted = True | |
if access_granted: | |
file = getattr(obj, file, None) | |
if file: | |
response = HttpResponse() | |
response['Content-Type'] = content_type | |
response['X-Accel-Redirect'] = file.url | |
response["Content-Disposition"] = '{0}; filename="{1}"'.format( | |
display_mode, file.name | |
) | |
return response | |
return HttpResponseForbidden("Can't access this media.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment