Reputation: 187
I am going to build a Django storage application where users can upload files to the server. Users also can download their files from the server. To download the file, the server returns the URL of the media file to the user. I added a permission class, if the user is authenticated & owner of the file then return the URL of the media file, otherwise return 404. But there is a problem, if any unauthenticated user found the URL of the media file from the history of the browser, then he can download/access the file. How can I handle this case?
Upvotes: 11
Views: 1889
Reputation: 195
I personally liked what Michal Májský suggested in his blog here:
from django.conf.urls import patterns, include, url
from django.contrib.auth.decorators import login_required
from django.views.static import serve
from django.conf import settings
@login_required
def protected_serve(request, path, document_root=None, show_indexes=False):
return serve(request, path, document_root, show_indexes)
urlpatterns = patterns('',
url(r'^%s(?P<path>.*)$' % settings.MEDIA_URL[1:], protected_serve, {'document_root': settings.MEDIA_ROOT}),
)
This is just verifies that any request to the media folder will go through authentication check, right from the urls.py
Upvotes: 1
Reputation: 71
The problem you're mentioning is not related to your backend application. It's related to the web server serving your media files (e.g. Nginx). In order to handle this problem, you should generate secure links from your django app which are bound to specific user IPs and have an expiration time. You can read this article for more info: https://www.nginx.com/blog/securing-urls-secure-link-module-nginx-plus/
Upvotes: 1
Reputation: 361
Django's development server does not deal with static/media files please take a look at this django-sendfile
Upvotes: 0