Skip to content

Instantly share code, notes, and snippets.

@ziad-saab
Last active October 4, 2021 15:52
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ziad-saab/41eca04a72d8038493ba to your computer and use it in GitHub Desktop.
Save ziad-saab/41eca04a72d8038493ba to your computer and use it in GitHub Desktop.
Get a list of a user's roles from Parse, including child roles, up to a certain depth
// Maximum depth is 3, after that we get a "" error from Parse
function getUserRoles(user) {
var queries = [
new Parse.Query('_Role').equalTo('users', user)
];
for (var i = 0; i < 2; i++) {
queries.push(new Parse.Query('_Role').matchesQuery('roles', queries[i]));
}
return user.rolesPromise = Parse.Query.or.apply(Parse.Query, queries).find().then(
function(roles) {
return roles.map(function(role) {
return role.get('name');
});
}
);
}
@haroonKhan-10p
Copy link

what is user here ? the whole object stored in req.user?

@aacassandra
Copy link

thanks bro

@macarthuror
Copy link

I think you can do it with less lines of code 😅

In a cloud Function

Parse.Cloud.define('getRoles', async (request) => {
    const query = await new Parse.Query(Parse.Role).equalTo('users', request.user).find()
    return query
})

In a JS client

async function getUserRoles () {
    const query = await new Parse.Query(Parse.Role).equalTo('users', Parse.User.current() ).find()
    return query
}

This will return an array with all the Roles of the User.
Hope this help you 👌😁

@coderofsalvation
Copy link

coderofsalvation commented Dec 5, 2019

@macarthuror i love terse refactors, however the description mentions , including child roles, up to a certain depth (which is lacking in your version). Your code only returns unnested roles.

@dsyrstad
Copy link

dsyrstad commented Oct 4, 2021

If anyone is here in 2021 looking for a TS version of this:

  static async getUserRoles(user: Parse.User): Promise<string[]> {
    const queries = [
      new Parse.Query(Parse.Role).equalTo('users', user),
    ];

    for (let i = 0; i < 10; i++) {
      queries.push(new Parse.Query(Parse.Role).matchesQuery('roles', queries[i]));
    }

    const roles = await Parse.Query.or(...queries).find({ useMasterKey: true });
    return roles.map((role) => role.getName());
  }

@coderofsalvation
Copy link

Hm it is somewhat confusing that you're asking for a TS version of a TS snippet. What is the real problem/context behind your question?

@dsyrstad
Copy link

dsyrstad commented Oct 4, 2021

@coderofsalvation No question from me. I just posted my TS version of the code, in case anyone needed it.

@coderofsalvation
Copy link

hehe indeed my bad 😂

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