Django Protected Media Files


https://b0uh.github.io/protect-django-media-files-per-user-basis-with-nginx.html

urls.py

from myproject.views import media_access

urlpatterns = [
    ...,
    url(r'^media/(?P<path>.*)', media_access, name='media'),
]

views.py

from django.http import HttpResponse
from django.http import HttpResponseForbidden

def media_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
    """

    access_granted = False

    user = request.user
    if user.is_authenticated():
        if user.is_staff:
            # If admin, everything is granted
            access_granted = True
        else:
            # For simple user, only their documents can be accessed
            user_documents = [
                user.identity_document,
                # add here more allowed documents
            ]

            for doc in user_documents:
                if path == doc.name:
                    access_granted = True

    if access_granted:
        response = HttpResponse()
        # Content-type will be detected by nginx
        del response['Content-Type']
        response['X-Accel-Redirect'] = '/protected/media/' + path
        return response
    else:
        return HttpResponseForbidden('Not authorized to access this media.')

Nginx

upstream myprojectapp {
  server localhost:8080;
}

server {
    listen 80;

    server_name myproject.com;

    server_name_in_redirect on;
    error_log /var/log/nginx/myproject-error.log crit;
    access_log  /var/log/nginx/myproject-access.log custom_combined;

    root /path/to/my/django/project/static;

    location ^~ /static/ {
        alias /path/to/my/django/project/static/;
    }

    location /protected/ {
        internal;
        alias /path/to/my/django/project/;
    }

    location / {
        include proxy_params;
        proxy_pass http://myprojectapp;
        proxy_buffering off;
    }

}


Did you find this article useful?