I am unable to fetch the hash and salt values from the database. They are being stored during the sign up, but not being retrieved from the application. Attached below are the snapshots of the database, console screen that displays the retrieved information of the user (which is without the salt and hash values) and the user schema and the code used to fetch the data.
Snapshot of the user data in the database (MongoDB)
snapshot of the same user data on the console Note: The isVerified is changed to true after the email is verified (The snapshot of the database was taken after the account was verified)
Schema method to validate the user
UserSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, `sha512`).toString(`hex`);
if(this.hash === hash){
return true;
}
return false;
};
Below is my user schema
const UserSchema = mongoose.Schema({
username: {
type: String,
required: true
},
email: {
type: String,
unique: true,
required: true
},
roles: {
type: 'String',
default: 'user'
},
isVerified: {
type: Boolean,
default: false
},
hash: String,
salt: String,
token: String,
passwordResetToken: String,
passwordResetExpires: Date
});
Code used to fetch the user
User.findOne({
username: req.body.username
}, (err, user) => {
console.log(user.validPassword(req.body.password) + " <<<<-------validPassword method result");
if (user === null) {
req.flash("error", "The provided username is incorrect. Please try again");
res.redirect("/login");
}
if (user.isVerified) {
if (user.validPassword(req.body.password)) {
res.redirect("/");
} else {
req.flash("error", "Incorrect password. Please try again");
res.redirect("/login");
}
} else if (!user.isVerified) {
console.log("user not verified");
req.flash("error", "Please confirm your email first by clicking on the activation link that was sent to you during registration");
res.redirect("/login");
}
});
The error is,
The "salt" argument must be one of type string, Buffer, TypedArray, or DataView. Received type undefined`.
I believe this is because salt is not being fetched from the database.