我遇到一个问题,我必须安全地让登录用户从指定路径访问本地目录内容。 / DjangoApp / media / user1 ,即当user1登录时,他们应该只能从 / DjangoApp / media / user1
访问内容我目前的观点是:
def get_absolute_pathname(pathname='', safe=True):
if not pathname:
return os.path.join(MEDIA_ROOT, 'index')
if safe and '..' in pathname.split(os.path.sep):
return get_absolute_pathname(pathname='')
return os.path.join(MEDIA_ROOT, pathname)
@login_required
def retrieve_path(request, document_root, pathname=''):
pathname = None
if request.user.is_authenticated():
pathname = request.user.get_username()
abs_pathname = get_absolute_pathname(pathname)
url = document_root
response = HttpResponseRedirect(url)
return response
当前网址为:
url(regex = r'^%s(?P<path>.*)$' % settings.STATIC_URL[1:],
view = 'django.views.static.serve',
kwargs = { 'document_root': '/home/www/abc/DjangoProject/media/',
'show_indexes' : True}),
url(r'^user1/(?P<pathname>.*)$', 'logd.views.retrieve_path', {
'document_root': 'http://127.0.0.1:8000/DjangoApp/static/user1',
}),
url(r'^user2/(?P<pathname>.*)$', 'logd.views.retrieve_path', {
'document_root': 'http://127.0.0.1:8000/DjangoApp/static/user2',
}),
url(r'^user3/(?P<pathname>.*)$', 'logd.views.retrieve_path', {
'document_root': 'http://127.0.0.1:8000/DjangoApp/static/user3',
}),
url(r'^user4/(?P<pathname>.*)$', 'logd.views.retrieve_path', {
'document_root': 'http://127.0.0.1:8000/DjangoApp/static/user4',
}),
我可以直接从网址访问http://127.0.0.1:8000/DjangoApp/static/。但我想限制访问。
我做错了什么以及如何对访问进行身份验证并且仅限于固定路径?
谢谢
答案 0 :(得分:0)
安全媒体文件不能由匿名用户提供更好的网址保护......
使用@ login_required
和def protected_serve(request, path, document_root=None):
您可以保护它..
了解更多信息How to to make a file private by securing the url that only authenticated users can see