implement custom serve_protected_media function to serve protected media files

This commit is contained in:
Yogesh Ojha
2024-07-04 09:15:01 +05:30
parent bd95609795
commit 2570004255
3 changed files with 32 additions and 2 deletions
+1
View File
@@ -159,6 +159,7 @@ USE_TZ = True
DJANGO_CELERY_BEAT_TZ_AWARE = False
MEDIA_URL = '/media/'
MEDIA_ROOT = '/usr/src/scan_results/'
FILE_UPLOAD_MAX_MEMORY_SIZE = 100000000
FILE_UPLOAD_PERMISSIONS = 0o644
STATIC_URL = '/staticfiles/'
+10 -2
View File
@@ -8,6 +8,8 @@ from drf_yasg import openapi
from drf_yasg.views import get_schema_view
from rest_framework import permissions
from reNgine.views import serve_protected_media
schema_view = get_schema_view(
openapi.Info(
title="reNgine API",
@@ -53,5 +55,11 @@ urlpatterns = [
include(
'api.urls',
'api')),
] + static(settings.MEDIA_URL, document_root=settings.RENGINE_RESULTS) + \
static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
path(
'media/<path:path>',
serve_protected_media,
name='serve_protected_media'
),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
# ] + static(settings.MEDIA_URL, document_root=settings.RENGINE_RESULTS) + \
+21
View File
@@ -0,0 +1,21 @@
import os
import mimetypes
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, Http404
from django.conf import settings
@login_required
def serve_protected_media(request, path):
file_path = os.path.join(settings.MEDIA_ROOT, path)
if os.path.isdir(file_path):
raise Http404("File not found")
if os.path.exists(file_path):
content_type, _ = mimetypes.guess_type(file_path)
response = HttpResponse()
# response['Content-Disposition'] = f'attachment; filename={os.path.basename(file_path)}'
response['Content-Type'] = content_type
response['X-Accel-Redirect'] = f'/protected_media/{path}'
return response
else:
raise Http404("File not found")