问题
I have a Django application that allows web visitors to create there own accounts. Once they create an account with a passwords, they should receive and email containing activation code. When a web-visitor creates a new account, they need to receive an activation email containing a unique key.
Obviously, I can do all this using Django's built-in authentication system. I've done it before without any problems. However, in this application, I don't want to pollute my Users table with inactive users. I only want activated users to appear in the Users table. So although I will use Django's account system for authenticating activated users, until they become activated, I'm rolling my own system. I'm keeping all the data about not-yet-activated users in a separate Django Model object (called UserActivation
). And I will be managing the sending of the activation email myself.
The problem I'm having is that I don't want to store the user-submitted password in Plain text. I want to store it in my UserActivation object in a field called "password" in the same hashed-format it would appear in the User table. To put it into the user object, I would have done myUser.set_password("plainTextPassword")
. How can I get this same value and stuff it into UserActivation.password
?
From looking at this doc, it seems that there is a make_password()
function that returns the value that I need. But I still need a User object to call that method. How can I conver "plainTextPassword"
to hashed password without going through the User object?
回答1:
You are on the right track. However you can manage the password manually using
from django.contrib.auth.hashers import make_password
print "Hashed password is:", make_password("plain_text")
Hasher configuration will be driven by PASSWORD_HASHERS which should be common for both the auth system and your UserActivation model. However you can pass it in make_password
method also.
PASSWORD_HASHERS = (
'myproject.hashers.MyPBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2PasswordHasher',
'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher',
'django.contrib.auth.hashers.BCryptSHA256PasswordHasher',
'django.contrib.auth.hashers.BCryptPasswordHasher',
'django.contrib.auth.hashers.SHA1PasswordHasher',
'django.contrib.auth.hashers.MD5PasswordHasher',
'django.contrib.auth.hashers.CryptPasswordHasher',
)
Hope this helps.
Read this link for more details: https://docs.djangoproject.com/en/dev/topics/auth/passwords/
回答2:
The accepted answer was helpful to me - I just wanted to add the check_password call (for people like me, who haven't used this functionality before)
from django.contrib.auth.hashers import make_password, check_password
hashed_pwd = make_password("plain_text")
check_password("plain_text",hashed_pwd) # returns True
来源:https://stackoverflow.com/questions/25098466/how-to-store-django-hashed-password-without-the-user-object