Can I use Django to prevent direct access to an image file?

后端 未结 2 535
甜味超标
甜味超标 2021-01-19 17:22

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

相关标签:
2条回答
  • 2021-01-19 17:48

    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

    class GatedContent(object):
    """
    Prevents specific content directories and types 
    from being exposed to non-authenticated users
    """
    
    def process_request(self, request):
       path = request.path
       user = request.user # out of the box auth, YMMV
    
       is_gated = False
       for gated in settings.GATED_CONTENT:
          if path.startswith(gated) or path.endswith(gated):
              is_gated = True
              break
      # Validate the user is an authenticated/valid user
      if is_gated and not user.is_authenticated():
          # Handle redirect
    
     
    
    0 讨论(0)
  • 2021-01-19 17:58

    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.

    0 讨论(0)
提交回复
热议问题