-1" to display all re..." /> -1" to display all re..." /> -1" to display all re..."/>

show records based on user role

79 Views Asked by At

I have a app which has roles e.g "user,admin". In the controller I check if the user is admin "req.user.roles.indexOf('admin') > -1" to display all records otherwise display only users records. I was wondering if there is a better way of doing this or is this the way to go. Thanks

code

    /**
 * List of Articles
 */
exports.list = function (req, res) {
  if (req.user.roles.indexOf('admin') > -1) {
    Article.find().sort('-created').populate('user', 'displayName').exec(function (err, articles) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(articles);
      }
    });
  }else {
    Article.find({user:req.user._id}).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
      if (err) {
        return res.status(400).send({
          message: errorHandler.getErrorMessage(err)
        });
      } else {
        res.json(articles);
      }
    });
  }
};
1

There are 1 best solutions below

0
On BEST ANSWER

You can also refactor out the database access bit in another method (probably in a different module - userController), which will make your code more readable. This doesn't qualify as an answer but putting all this in comment didn't look ok.

exports.list = function (req, res) {
  if (hasRole('admin')) {
    userController.getAllRecords(req, res);
  } else {
    userController.getRecordsById(req, res)
  }
};