Python Django安全用户到本地系统目录映射
我有一个问题,我必须安全地让登录用户从指定路径访问本地目录内容/DjangoApp/media/user1,即当user1登录时,他们应该只能从/DjangoApp/media/user1访问内容 我目前的看法是:Python Django安全用户到本地系统目录映射,python,django,authentication,django-views,Python,Django,Authentication,Django Views,我有一个问题,我必须安全地让登录用户从指定路径访问本地目录内容/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.
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为:
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',
}),
我可以直接从url访问。但我想限制访问
我做错了什么?如何使访问经过身份验证并仅限于固定路径
谢谢保护媒体文件不被匿名用户提供更好的url保护 使用@login\u required和def protected\u serverequest、path、document\u root=None:您可以保护它
有关更多信息,请参考此问题,以便了解@RajaSimon我的实现与此类似。但正如您在评论中提到的,任何登录用户都可以通过更改url访问所有数据。i、 例如,将user1更改为user2。有没有办法限制用户1只能访问名为user1的目录。等一下,我会更新..我用更安全的文件服务更新了我的答案。。。只有已登录的用户才能访问其文件。。。请看一看,并给予学分…谢谢@RajaSimon它成功了