I\'m using Node.js + Express + Passport to create a simple authentication(local)
and what I\'ve reached so far that when a wrong username or password entered user is re
Also being a noob at this, it took me a whole day to figure this one out. I used the history from another one of Jared's example apps and some crypto advice from folks on here.
First off I made a method that generates a salt (a big random number which is stringified), uses the salt and the user's password to create a hash (with the help of the nodejs 'crypto' module), and finally stores both the salt and the hash every time before mongoose saves a new account.
//make hash
userSchema.pre('save', function(next) {
var user = this;
if(!user.isModified('password')) return next();
var rand = (Math.floor(Math.random() * 1000000000)).toString(36);
var hash = crypto.createHash('md5').update(user.password + rand).digest("hex");
user.password = hash;
user.salt = rand;
next();
});
For the verification I simply take the inputted password (at login) and attempt the make the same hash again using the salt. I then compare the stored hash to the new one and return true or false accordingly.
// Password verification
userSchema.methods.validPassword = function(password) {
var testhash = crypto.createHash('md5').update(password + this.salt).digest("hex");
if(testhash === this.password) {
return true;
} else {
return false;
}
}