1

I'm trying to check user access level to grant him some actions in the service.

exports.hasAdminAccess = function(req, res, next) {
  if (hasAccessLevel(req.user, adminLevel)) {
    return next()
  }
  res.redirect('/accessProblem');
}

function hasAccessLevel(user, level) {
  UserRole = models.UserRole;
  return UserRole.findOne({
    where: {
      id: user.userRoleId,
    }
  }).then(function(role){
    if (role.accessLevel <= level) {
      return true;
    } else {
      return false;
    }
  });
}

but hasAccessLevel() is constantly returning Promise object instead true or false.

I could write body of hasAccessLevel in hasAdminAccessLevel, but I have plenty of other methods for other roles.

Are there any other ways to perform this operation?

codejockie
  • 9,020
  • 4
  • 40
  • 46
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Yury Tarabanko Dec 29 '17 at 16:52

1 Answers1

1

You could resolve the promise in the hasAdminAccess method like below:

exports.hasAdminAccess = function(req,res,next) {
  hasAccessLevel(req.user,adminLevel)
    .then((value) => {
       if (value) {
          return next();
       }
    })
    .catch(() => res.redirect('/accessProblem'));
}

function hasAccessLevel(user, level) {
  UserRole = models.UserRole;
  return UserRole.findOne({
    where: {
      id: user.userRoleId,
    }
  }).then(function(role){
    if (role.accessLevel <= level) {
      return true;
    } else {
      return false;
    }
  });
}
codejockie
  • 9,020
  • 4
  • 40
  • 46