Skip to content Skip to sidebar Skip to footer

Can I Use Django To Prevent Direct Access To An Image File?

I'd like to prevent my web users from simply right clicking an image and copying/sharing the URL. Certain authenticated users have access to certain images, and I'd like to enforc

Solution 1:

I'll bite.

Session Middleware - not elegant, but it will work

You'll want the images you don't want served publicly to not be served through your standard apache/django static files config.

your session middleware can then check all incoming requests for the path and if the path is your image directory (such as /privateimg/) and the user is not authenticated you can bounce them back out or replace it inline with another image (such as one that has a watermark).

You can check out the django docs on how session middleware works https://docs.djangoproject.com/en/dev/topics/http/sessions/

People can still pass your links around, but only authenticated users can actually see the contents of said links (called gating your content)

To elaborate:

settings.py

GATED_CONTENT = (
    '/some_content_dir/', # This is a directory we want to gate'.pdf', # maybe we want to gate an entire content type
)

MIDDLEWARE_CLASSES = (
    ...  # Out of the box middleware...blah blah'yourapp.somemodule.sessionmiddleware.GatedContent',
)

Then you have the following app structure

yourapp
   |-somemodule
        |-sessionmiddleware.py

Now to the meat (yum!)

sessionmiddleware.py

classGatedContent(object):
"""
Prevents specific content directories and types 
from being exposed to non-authenticated users
"""defprocess_request(self, request):
   path = request.path
   user = request.user # out of the box auth, YMMV

   is_gated = Falsefor gated in settings.GATED_CONTENT:
      if path.startswith(gated) or path.endswith(gated):
          is_gated = Truebreak# Validate the user is an authenticated/valid userif is_gated andnot user.is_authenticated():
      # Handle redirect

Solution 2:

You might be interested in XSendfile.

This is most [elegant and] performance choice IMO: actual files will be served by you webserver, while access control to this files will be done using your Django app.

You may google for "django xsendfile", there are lot of useful posts.

Post a Comment for "Can I Use Django To Prevent Direct Access To An Image File?"