Sorry if this turns out for me to be missing something really obvious, but I've been running into issues with this code for some time and I"m just not getting it. I'm currently trying to work on an authentication system for an app I'm developing for school, and to do that I'm making an API endpoint that takes an inputted password, hashes it, then compares it the stored hashed password to see if the two match. My current code looks like this:
router.route('/auth/').post((req, res) => {
const userName = req.body.userName;
const password = User.generateHash(req.body.password);
let query = User.findOne({"userName": userName},{_id:0, userType:0, fName:0, lName:0, password:1, email:0, userName:0, __v:0});
let serverpass = query.get("password");
if (serverpass == password) {
res.status(200).json("User Authenticated!");
} else {
res.status(400).json("Passwords do not match." + password + " " + serverpass)
}
})
Based on what I read, the findOne() method returns a non-cursorable document you're capable of getting values from using the .get() method. However, whenever I test it using a REST client the serverpass variable always comes back as an object of type Object and the get() method always returns undefined. Any help on this would be appreciated. For reference, here is the database entry I'm trying to read:
{
"_id": *REDACTED*,
"userType": "AuthTest",
"fName": "Auth",
"lName": "Test",
"password": *REDACTED*,
"email": "[email protected]",
"userName": "AuthTest",
"__v": 0
},
where the password is just "password" hashed. The supplied information to the REST client is:
{
"userName":"AuthTest",
"password":"password"
}
Thanks!
.get()? I don't think it will work because Mongo queries are async. This code is synchronous..execdocs.