Assign role to user after signup

Hi, i’m learning parse and i’m trying to create a simple game, for that I created a role called “player” and assigned class level permissions to that role.

So next thing I want to do is to use a cloud code afterSave, to assign the player role to every new user. This is what I got so far:

Parse.Cloud.afterSave(Parse.User, (request) => {
  var user =  request.object.id;
  var query = new Parse.Query(Parse.Role);
  query.equalTo("name", 'player')
    .then(function(roles) {
      roles.getUsers().add(user)
      return roles.save();
    })
});
Parse.Cloud.afterSave(Parse.User, request => {
  var query = new Parse.Query(Parse.Role);
  query
    .equalTo("name", "player")
    .first({ useMasterKey: true })
    .then(function(role) {
      await role
        .relation("users")
        .add(request.object)
        .save(null, { useMasterKey: true });
    });
});

This should work. I don’t know if you need to use the masterkey to modify the user roles or get roles, by default, but I’ve added just to be sure

This make more sense than my code, but is not working yet, also I am confused, can one use await inside .then or shouldn’t that be inside an async function?

I added async just in case and it seems to be working now

Parse.Cloud.afterSave(Parse.User, request => {
  var query = new Parse.Query(Parse.Role);
  query
    .equalTo("name", "player")
    .first({ useMasterKey: true })
    .then( async function(role) {
      await role
        .relation("users")
        .add(request.object)
        .save(null, { useMasterKey: true });
    });
});

I’ve forgot to add the async word :laughing:

Thanks , I really appreciate your help!

1 Like