0

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.

Omar Hussein
  • 1,057
  • 2
  • 13
  • 31
  • Checkout https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call?rq=1 - although it is originally for AJAX, it is much the same thing as you are facing here. – abondoa Apr 11 '20 at 21:40
  • If you want to know when `verifyOwnership()` is done, then it must either accept a callback that it calls to tell the caller when it's done or it needs to return a promise that it resolves when it's done and the caller uses that promise. Those are your choices. Standard asynchronous design in node.js - promise, callback or in some cases, an event. – jfriend00 Apr 11 '20 at 22:12

0 Answers0