I am converting my code from parse.com to parse-server with little success. The idea of the afterSave function is to assign user only ACL and assign the user to the 'user' role.
The ACL part works fine, however I am unable to assign the user to the role.
Parse.Cloud.afterSave(Parse.User, function(req, res) {
if (!req.object.existed()) {
var user = req.object;
var acl = new Parse.ACL(user);
acl.setReadAccess(user, true);
acl.setWriteAccess(user, true);
user.setACL(acl);
return user.save({}, { useMasterKey: true }).then(function() {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", 'user');
return query.first({useMasterKey: true});
}).then(function(roles) {
if (roles.length < 1) return Parse.Promise.error("no such role");
roles[0].getUsers({useMasterKey: true}).add(user);
return roles[0].save({}, { useMasterKey: true });
}).then(function() {
return user;
});
}
});
"however I am unable to assign the user to the role". add function(err) to see which step failed, and see error message.
The code you shows is incorrect.
try this one
return user.save({}, { useMasterKey: true }).then(function() {
var query = new Parse.Query(Parse.Role);
query.equalTo("name", 'user');
return query.first({useMasterKey: true});
//first will return one object or null
}).then(function(role) {
//.getUsers() is equal .relation('users')
if(role){
role.getUsers().add(user);
return role.save(null, { useMasterKey: true });
}else{
return Parse.Promise.error("no such role");
}
}, console.error).then(function() {
return user;
}, console.error);