Object.save({ useMasterKey: true }) in cloud functions?

I’m using this cloud function to let an admin assign/change Roles to users:

// change user role
Moralis.Cloud.define('changeRole', async (request) => {
  if (!await validateUserRole(request.user, 'Administrator')) throw "No access" // validate user role
  const userQuery = new Moralis.Query(Moralis.User);
  userQuery.equalTo('objectId', request.params.userId);
  const userObject = await userQuery.first({useMasterKey:true});
  const roleQuery = new Moralis.Query(Moralis.Role)
  const roles = await roleQuery.find({ useMasterKey: true })
  for (let i = 0; i < roles.length; i++) {
    if (roles[i].get('name') === request.params.roleName) {
    } else {
  return request.params.roleName
  fields : ['roleName', 'userId'],
  requireUser: true

It works fine, but I cannot set the CLP of the Role class to anything less than Public write, which makes no sense.
It’s because the object.save() function has no access and doesn’t work with { useMasterKey: true } to override the CLP.
Am I using the wrong approach?

1 Like

Hey @matiyin

{ useMasterKey: true } gives an ability to override, read and etc even protected fields.

There is a mistake in saving logic.
Give me some time and I’ll debug the code. :wink:

1 Like

Cheers @Yomoo

could it be that { useMasterKey: true } doesn’t work at all at the moment to override CLP?
I get

Error: Permission denied, user needs to be authenticated.
    at handleError (RESTController.js?bdb0:437)

when using

  const tokenQuery = new Moralis.Query('EthNFTOwners')
  const queryResults = await tokenQuery.find({ useMasterKey: true })

with CLP Public read/write/add set to off on EthNFTOwners
on server v0.0.242


I’ve checked and it works fine.

When a Cloud Code function is called, it can use the optional {useMasterKey:true} parameter to gain the ability to modify user data. With the master key, your Cloud Code function can override any ACLs and write data. This means that it’ll bypass all the security mechanisms you’ve put in place in the previous sections

Where from you have tried to run this code? From the frontend or from console in the Dashboard?

Turns out you need to use this for overrides:

object.save(null, { useMasterKey: true })

instead of

object.save({ useMasterKey: true })

Would be cool if that was explained somewhere. I found it in your Job example, which was very helpful thanks!

Ignore my previous remark about { useMasterKey: true } not working anywhere, I think it was a temporary hiccup in the system: :slight_smile:



We already have this in docs Using the Master Key in cloud code:

Yeah, yesterday there were some problems with cloud code working
But now it works nice as always :man_factory_worker:

Happy BUIDLing :man_mechanic: