How to to make a file private by securing the url that only authenticated users can see

前端 未结 3 1808
花落未央
花落未央 2020-12-08 16:43

I was wondering if there is a way to secure an image or a file to be hidden when it is not authenticated.

Suppose there is an image in my website which can only be s

3条回答
  •  -上瘾入骨i
    2020-12-08 17:31

    By securing any media file not to serve by anonymous user, better way url protection.

    Code ( Updated ):

    from django.conf.urls import patterns, include, url
    from django.contrib.auth.decorators import login_required
    from django.views.static import serve
    from django.conf import settings
    
    from django.core.exceptions import ObjectDoesNotExist
    from django.shortcuts import HttpResponse
    
    @login_required
    def protected_serve(request, path, document_root=None):
        try:
            obj = Photobox.objects.get(user=request.user.id)
            obj_image_url = obj.image.url
            correct_image_url = obj_image_url.replace("/media/", "")
            if correct_image_url == path:
                return serve(request, path, document_root)
        except ObjectDoesNotExist:
            return HttpResponse("Sorry you don't have permission to access this file")
    
    
    url(r'^{}(?P.*)$'.format(settings.MEDIA_URL[1:]), protected_serve, {'file_root': settings.MEDIA_ROOT}),
    

    Note: previously any logged in user can access any page, now this update restrict non user to view other files...

提交回复
热议问题