0

I'm trying to protect certain files from outside users. After reading a bunch of posts and questions here, I came up with a solution that doesn't require adjusting server settings, and seemed within my technical level of understanding. But after all that research, my solution seems a bit too easy. So, I wanted to come here and see if this makes sense, is somewhat secure, and what holes I'm missing.

I'm uploading the files I'm concerned about to a folder called protected within the media directory in this example.

Here is my urls.py file:

import re
from . import views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.auth.decorators import login_required
from django.shortcuts import HttpResponseRedirect
from django.urls import path
from django.views.static import serve
from django.contrib.auth import views as auth_views

@login_required
def serve_protected_media(request, path, document_root=None, show_indexes=False):
    return serve(request, path, document_root, show_indexes)

def protected_serve(request, path, document_root=None, show_indexes=False):
    if re.match(r'^protected', path):
        return serve_protected_media(request, path, document_root, show_indexes)
    else:            
        return serve(request, path, document_root, show_indexes)

urlpatterns = [
    path('', views.index, name='site_index'),
    path('admin/', admin.site.urls),
    path('hr/', include('hr.urls')),
    path('accounts/login/', auth_views.login, name='login'),
    path('accounts/logout/', auth_views.logout, name='logout', kwargs={'next_page': '/'}),
] + static(settings.MEDIA_URL, protected_serve, document_root=settings.MEDIA_ROOT)

It works for me with some testing, but my overall question is: Is this a decent approach to protecting certain files from the world outside of logged-in users?

Edit: In addition, at this time I'm not very concerned with Django serving files, as the files in question aren't very large, and this application does not need to scale (internal HR use only).

hookedonwinter
  • 12,436
  • 19
  • 61
  • 74
  • 1
    This approach is perfectly fine given your requirements. – Kevin Lee Oct 19 '18 at 18:35
  • 1
    For a large site you'd want to use sendfile for this (https://stackoverflow.com/questions/1156246/having-django-serve-downloadable-files), but your solution should work well for smaller loads. – thebjorn Oct 19 '18 at 18:44

0 Answers0