Checking for (admin) role via CloudCode validation

Would this be something you guys recommend to check for the admin role (or any other role for that matter). Anything wrong with this? This would simply check the user calling the method, see if he has that role, and return true if he does, or throw an error if not.

Parse.Cloud.define("isAdmin", async (request) => {
	return true
}, {
    requireAnyUserRoles: ["admin"]
});

making use of Parse-Server’s validation requireAnyUserRoles.

I don’t see any problem with that.

1 Like

The only problem is that the code will throw an error if the user is not an admin, meaning that your frontend code will look something like:

let isAdmin = false;
try { 
  isAdmin = await Parse.Cloud.run('isAdmin');
} catch (e) {
  // error could be for other reasons
  isAdmin = false;
}

I think a better approach would be:

Parse.Cloud.define("isAdmin", async ({ user }) => {
  if (!user) {
    return false;
  }
  const admin = new Parse.Query(Parse.Role)
    .equalTo("name", "admin")
    .equalTo("users", user)
    .first({ useMasterKey: true });
  return !!admin;
});

That way your client code is simply:

const isAdmin = await Parse.Cloud.run('isAdmin');

Following up on @dblythy’s solution, a minimal optimization is to use count() instead of first(), so that isAdmin = (count === 1). No idea if the difference in performance is even measurable, but I have a better feeling when no unused data is being transmitted :sweat_smile: