如何在 Django 中限制对媒体图像 URL 的访问

how can restrict access to media image URL in django

如何限制对媒体图像 url 的访问,并使其只能由 django 中的访问所有者用户访问,

这是我的 class 模型:

class private_image(models.Model):
    i_user = models.OneToOneField(User, related_name='related_PRF_user', on_delete=models.CASCADE)
    i_image= models.ImageField(upload_to='images', blank=True, null=True )

我的媒体设置是:

MEDIA_ROOT = os.path.join(BASE_DIR, 'media_root/')
MEDIA_URL = '/media_url/'

例如:我不希望用户将图像 url 像这样“http://127.0.0.1:8000/media_url/images/67155_0_AVemgEZ.jpg”放在他们的浏览器中并打开图像, 如果请求用户不是同一所有者用户。

我相信,我可以做一个小函数来检查访问用户并请求 URL '/media_url/images/' 来获取图像名称,然后使用图像名称和从数据库中获取对象 然后检查所有者(i_user)是否具有相同的访问用户。

但是我如何告诉 Django 在服务 MEDIA_URL 请求之前使用这个函数。

如果您有示例,那将非常有帮助。

提前致谢

media 的所有 requests 都应该经过特定的视图。

myproject/urls.py:

from myproject.views import media_access

urlpatterns = [
    ...,
    path('media_url/images/<str:path>', media_access, name='media'),
    # or
    # url(r'^media_url/(?P<path>.*)', media_access, name='media'),
]

添加视图并检查访问权限。

myproject/views.py:

from django.http.response import FileResponse
from django.http import HttpResponseForbidden

def media_access(request, path):    
    access_granted = False

    user = request.user
    if user.is_authenticated():
        if user.is_staff:
            # If admin, everything is granted
            access_granted = True
        else:
            # For simple user, only their documents can be accessed
            doc = user.related_PRF_user.i_image  #Customize this...

            path = f"images/{path}"
            if path == doc:
                access_granted = True

    if access_granted:
        response = FileResponse(user.related_PRF_user.i_image)
        return response
    else:
        return HttpResponseForbidden('Not authorized to access this media.')

请告诉我这是否有效..