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 ca开发者_如何学运维n 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?
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.
精彩评论