在 Django 站点中使用任意密码保护任意页面的最佳方法?
我有一个 Django 网站,人们可以在其中上传和共享他们的文件。每个文件都有自己的页面。我想让人们能够为每个文件设置密码,这样人们只有输入正确的密码才能查看该文件的页面。所以基本上,用户将转到文件的页面,如果该文件受密码保护,用户将看到“密码”表单而不是文件,一旦正确输入密码,用户就可以看到该文件。同样重要的是,用户只需输入密码一次。
我的第一直觉是在文件模型中添加一个“密码”字段,但我不确定让用户输入密码的最佳方法,并在输入后让用户看到该文件的页面(我在想也许最好是一块饼干)。
这里有什么建议或最佳实践吗?是否有任何现有的应用程序可以实现类似的功能?
I have a Django site where people can upload and share their files. Each file is given its own page. I want to give people the ability to give each file a password so that people can only view that file's page if they enter the correct password. So basically, a user will go to a file's page, and if that file is password protected, the user will see a "password" form rather than the file, and once the password is correctly entered, then the user can see the file. It's also important that the user only has to enter the password once.
My first instinct is to just add a "password" field to the File model but I'm not sure of the best way to let a user enter the password and, once entered, let the user see that file's page (I was thinking maybe a cookie would be best).
Any tips or best practices here? Are there any existing apps for anything like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果每个文件都有密码,那么将密码哈希存储在文件模型中是合理的。我强烈建议您重新使用 django.contrib.auth 中的哈希方法,而不是自行构建。
为了在登录响应之外保留用户对文件的访问,您可以使用 Django 的内置会话框架:在会话对象中构建允许用户访问的文件列表。除非您希望同时为大量文件授权用户会话,否则这将很有效。
请注意,您可以将会话设置为使用 cookie 作为后端,这也将为您提供 cookie 的加密签名,可能比手卷 cookie 更好。
If you have a password per file, then it's reasonable to store the password hash in the File model. I would strongly recommend that you re-use the hashing methods from
django.contrib.auth
rather than rolling your own though.In order to persist the user's access to the file beyond the login response, you could use Django's built-in sessions framework: build a list of files the user is allowed to access within the session object. This will work well unless you're looking to authorize a user session for large numbers of files at the same time.
Note that you can setup the sessions to use a cookie as a backend, and this will also give you cryptographic signing of the cookie, likely to be better than a hand-rolled cookie.