How to to make a file private by securing the url that only authenticated users can see
Question: 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 seen if that user is
authenticated. But the thing is I can copy the url or open the image in the
new tab.

`http://siteis.com/media/uploaded_files/1421499811_82_Chrysanthemum.jpg`

And again, even if I am not authenticated, I can view that particular image by
going to that url. So, my question is or my problem is, how do I secure the
files, so that only authenticated users will see. I hope I was clear, if not
please ask. I will really appreciate if you could help me. And if possible in
a pythonic/django way. Thank you.

**Update:**

view:

    
    
    def pictures(request, user_id):
        user = User.objects.get(id=user_id)
        all = user.photo_set.all()
        return render(request, 'pictures.html',{
            'pictures': all
        })
    

models:

    
    
    def get_upload_file_name(instance, filename):
        return "uploaded_files/%s_%s" %(str(time()).replace('.','_'), filename)
    
    class Photo(models.Model):
        photo_privacy = models.CharField(max_length=1,choices=PRIVACY, default='F')
        user = models.ForeignKey(User)
        image = models.ImageField(upload_to=get_upload_file_name)
    

settings:

    
    
    if DEBUG:
        MEDIA_URL = '/media/'
        STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "static-only")
        MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "media")
        STATICFILES_DIRS = (
        os.path.join(os.path.dirname(BASE_DIR), "myproject", "static", "static"),
        )
    

**Update:**

template:

    
    
    {% if pictures %}
        {% for photo in pictures %}
            <img src="/media/{{ photo.image }}" width="300" alt="{{ photo.caption }}"/>
        {% endfor %}
    {% else %}
        <p>You have no picture</p>
    {% endif %}
    

url:

    
    
    url(r'^(?P<user_name>[\w@%.]+)/photos/$', 'pictures.views.photos', name='photos'),
    
    if settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
        urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    


Answer: 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<path>.*)$'.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...

