Let's imagine I have an MongoDB document that includes the following data:
{
"username": "test123",
"password": "$2b$10$M2Y3ELsgfvA4KHxdCJkezeHZ1kKgtOA2Jiq4kuwqcRJSovGBu9nLm"
}
The password is encrypted using bcrypt
. Using MongoDB's official Node driver, I can find the username with:
collection.findOne({ username: req.body.username });
But how can I find the username, then check the password
value of the same document (the password related to the username), and finally return the password?
PS. I know the title is very confusing, if you can think of a better way to express it, please comment below.
CodePudding user response:
It's bad practice to send encrypted passwords to the database. It has some security issues. I guess you want to get the user by its username, figure out if it's the right user that you fetched by comparing its password also (password hashes), then do something with that user - for example, return password or so, as you mentioned (I don't see why would you expose password back to anyone).
For encryption, I'm using bcryptjs
package, but it's pretty similar. Its function compare()
takes the raw password for the first argument, and takes hashed password from the database as the second argument. It hashes the raw password and compares it with the given hash. If hashes match, the password is valid. For a code, you would have something like:
const bcrypt = require('bcryptjs');
// ...
const user = await collection.findOne({ username: req.body.username });
if (!user) throw new Error('User doesn\'t exist');
// first argument "password" is a raw password to compare with the one in the document
const passwordValid = await bcrypt.compare(password, user.password);
if (!passwordValid) throw new Error('Invalid password');
// do whatever you want to do with validated user
// if you want password to return, raw "password" is the one that's in the database also (hash)
CodePudding user response:
collection.findOne({ username: req.body.username, password: encrypt(req.body.password) });
function encrypt(value)
{
...
}