alright, so I have a controller for my account entity, it has the following helper function
// Verify user accessing is account owner
const verifyOwnership = (account_id, owner_id) => {
Account.findById(account_id, function (err, account) {
if (err) return next(err);
if (account.owner_id != owner_id) {
return false;
}
console.log("here");
return true;
});
};
and my controller's account update function is as follows
exports.account_update = function (req, res, next) {
user_id = jwt.decode(req.headers["authorization"].slice(7)).id;
account_id = req.params.id;
// Verify user accessing is account owner
ownership_verified = verifyOwnership(req.params.id, user_id);
if (!ownership_verified) {
res.status(403).send({ error: "You are not allowed to access this account." });
return;
}
console.log(ownership_verified);
// Update account
Account.findByIdAndUpdate(account_id, { $set: req.body }, { new: true }, function (
err,
pet
) {
if (err) return next(err);
res.send({ message: "Account updated successfully.", account });
});
};
Now, I have a couple issues with this code:
The code does not wait for the verifyOwnership function to respond, the console log of ownership_verified logs undefined, then the "here" is logged. making the verifyOwnership function async/await just had it returns a promise instead, and therefore everything was handled as true, I'd like instead to WAIT for the verifyOwnership to return either a true or a false.
The second issue is more of a logic one related to mongoose, I'd like that if the verifyOwnership function does not find an account to begin with using provided ID, to return a 404 that no account was found, but to also stop the function that called it right there, not to proceed with the update nor send the "You are not allowed to access this account" message.
Sorry for the long post and thanks in advance.