Forums

How to secure Media URL ?

Hello, I am having a problem on how I was able to restrict users from accessing media files through media url. I have pdf files stored in the media, and these shouldn't be accessible by any user not unless they are authorized.

I was able to this in my localhost where I tweak and override the media url in urls.py:

 path('%s(?P<path>.*)' % settings.MEDIA_URL[1:], views.protected_serve, {'document_root': 
 settings.MEDIA_ROOT}),

and a function in my views.py that would validate and restrict the user. So if the user isn't authorized for the file, it will just through PermissionDenied() something when the user went to its media url.

 @login_required
 def protected_serve(request, path, document_root=None, show_indexes=False):
      user = request.user

      if user.is_staff and user.is_admin:
           return serve(request, path, document_root, show_indexes)
      else:
            raise PermissionDenied()

Everything was working in my localhost but it no longer works in my deployed app. I try to set debug to False and True but still no fix. Also, I suspect that the custom url doesn't seem to override the media url because when I tried to put a message dialogue inside the protected_serve function, no message shows each time I go to media url. Does this have something to do with the mapping of static and media files? please help huhuhu

also.... in settings.py this is my media url MEDIA_URL = '/media/' and media root MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') In mapping, i set url to /media/ and the directory is /home/technorepository/THESIS-ARCHIVE-DJANGO-PROJECT/media/.

If you have a URL in your web app that is aliased by a URL that you have set up in static files, then the static files one will always take precedence. If you want to secure a URL like that, use a different prefix than any of the static files mappings that you have.