save password as salted hash in mongodb in users collection using python/bcrypt
I don't know how you use mongodb to bring the data, but if you want to hash the pass it's as easy as:
from flask import Flask
from flask.ext.bcrypt import Bcrypt
app = Flask(__name__)
bcrypt = Bcrypt(app)
# Your code here...
users_doc = {
"username": "james",
"password": bcrypt.generate_password_hash(password)
}
And then if you want to check the password, you can use the check_password_hash()
function:
bcrypt.check_password_hash(users_doc["password"], request.form["password"]) # Just an example of how you could use it.
Generate a salt using bcrypt and keep it saved in your settings file:
import bcrypt
salt = bcrypt.gensalt()
To encrypt the password:
password = "userpassword"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())
Checking the generated salt:
>>> print hashed
$2a$12$C.zbaAxJPVVPKuS.ZvNQiOTVSdOf18kMP4qDKDnM3AGrNyGO5/tTy
To check if a given password matches the one you generated (just create a hash of the password using the salt and compare it to the one on the database):
given_password = "password"
hashed_password = bcrypt.hashpw(password, salt) #Using the same salt used to hash passwords on your settings
hashed_password == hashed #In this case it returns false, because passwords are not the same