1

I am trying to restrict those users, who directly hit on a absolute static image url path(www.xyz.com/static/img/sam.png) in browser and access it.

I tried with the following django docs:

https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/apache-auth/

But this will block those images which are there in login page also(before valid user is authenticated).

Is there any other efficient way to do restrict non logged-in users?

EDIT: I had referred to this Django: Serving Media Behind Custom URL but it is related to nginx and not apache. And also there is a difference b/w static and media content. My question is related to just static content

Community
  • 1
  • 1
Abijith Mg
  • 2,193
  • 16
  • 28

1 Answers1

5

you can try my answer here by just routing static url request to your own view (it tries to use sendfile extension available in almost all web servers) or use django whitenoise, whitenoise uses sendfile api which is server independent ( whether you are using nginx or apache) and production ready, extend the whitenoise middleware and add your checking there for file restriction, a sample code will be

  from django.http import HttpResponseForbidden
  from whitenoise.middleware import WhiteNoiseMiddleware
  # this is a sample code, you can change for your use case
  class ProtectedStaticFileMiddleware(WhiteNoiseMiddleware):
        def process_request(self, request):
            # check user authentication
            if condition_met(request):
               return super(WhiteNoiseMiddleware, self).process_request(request)
            # condition false
            return HttpResponseForbidden("you are not authorized")

NOTE: Serving files directly ( large files ) using python file chunks api is not a good idea when you are in production ( ideas like file.read() or FileResponse)

Community
  • 1
  • 1
Renjith Thankachan
  • 3,638
  • 1
  • 23
  • 41