save password as salted hash in mongodb in users c

2020-07-09 09:54发布

I want to generate a salted password hash and store it in MongoDB collection called users, like this:

users_doc = { 
    "username": "James",
    "password": "<salted_hash_password>"
}

I'm not sure how to generate the hashed password using Bcrypt, then when I login in my flask app, be able to check if the hash matches with the hashed password stored in MongoDB.

3条回答
女痞
2楼-- · 2020-07-09 10:33

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
查看更多
闹够了就滚
3楼-- · 2020-07-09 10:45

You can use the following the hash your password.

app.post("/register", function(req, res){
    var type = req.body.type
    var newUser = new Student({
        username: req.body.username,
        gender: req.body.gender,
        rollnumber: req.body.rollnumber,
        dob: req.body.dob,
        email: req.body.email,
        type: req.body.type,
        password: req.body.password
    })

    req.checkBody('username','UserName is Required').notEmpty();
    req.checkBody('rollnumber','Roll Number is Required').notEmpty();
    req.checkBody('email','Email Required').notEmpty();
    req.checkBody('email','Email Invalid').isEmail();
    req.checkBody('password','Password is Required').notEmpty();
    req.checkBody('password1','Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();
    if(errors){
        res.render('Sregister', {errors: errors});
    }else{
    bcrypt.genSalt(10, function(err,  salt){
        bcrypt.hash(newUser.password, salt, function(err, hash){
            if(!err){
                newUser.password = hash;
            }
            newUser.save(function(err){
                if(!err){
                    console.log("success in reg");
                    res.redirect("/student/login")
                }
            })
        })
    })

And use the following to compare the password while logging in.

passport.use('student', new LocalStrategy(function(username, password, done){
    var query = {username: username};
    Student.findOne(query, function(err, student){
        if(err) throw err;
        if(!student){
            return done(null, false);
        }
        bcrypt.compare(password,student.password, function(err, isMatch){
            if(err) throw err;
            if(isMatch)
                return done(null, student);
            else
                return done(null,false);
        })
    })
}))
查看更多
再贱就再见
4楼-- · 2020-07-09 10:52

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.
查看更多
登录 后发表回答