Skip to content

Instantly share code, notes, and snippets.

@pulkitsinghal
Created May 3, 2014 00:27
Show Gist options
  • Save pulkitsinghal/e2143da7e691831f5ea4 to your computer and use it in GitHub Desktop.
Save pulkitsinghal/e2143da7e691831f5ea4 to your computer and use it in GitHub Desktop.
Parse Cloud Code for checking if a user has the required role
Parse.Cloud.define('isAdmin', function(request, response){
if(!Parse.User.current()){
response.error('Request did not have an authenticated user attached with it');
}
else {
userHasRole(request.params.parseSessionToken, 'super') // ex: check if user has "super" role
.then(function(hasRole){
if(hasRole){
response.success({super: true});
}else{
response.success({super: false});
}
},
function(error){
console.error('Request failed: ' + JSON.stringify(error,null,2));
response.error('Request failed: ' + JSON.stringify(error,null,2));
});
}
});
var userHasRole = function(username, rolename) {
Parse.Cloud.useMasterKey();
var queryRole = new Parse.Query(Parse.Role);
queryRole.equalTo('name', rolename);
return queryRole.first({useMasterKey:true})
.then(function(roleObject){
var queryForUsername = roleObject.relation('users').query();
queryForUsername.equalTo('username', username)
return queryForUsername.first({useMasterKey:true})
.then(function(userObject){
if(userObject){
console.log(username + ' has role: ' + rolename);
return Parse.Promise.as(true);
}
else{
console.log(username + ' does not have role: ' + rolename);
return Parse.Promise.as(false);
}
});
});
}
@Tudodesk
Copy link

It would be easier to just create a permission table - add a row with the role when the user is created and then try to read that row with the users session key - no result - no permission.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment