Parse Cloud Functions - restrict access to single users

302 views Asked by At

I'm currently experimenting with Parse Cloud Functions.
The following simple example already worked well:

Parse.Cloud.define("hello", async (request) => {
    return "Hi " + request.params.name;
});

In my apps I login as a user before making any request so I want to restrict access to this function by objectId of the user.
The docs give the following example for validation:

requireUserKeys: {
    accType : {
      options: 'reviewer',
      error: 'Only reviewers can get average stars'
    }
  }

So I added this validation to my request (and I require masterKey for validation as normal users are not allowed to read User objects):

documentation

Parse.Cloud.define("hello", async (request) => {
    return "Hi " + request.params.name;
}, {
    validateMasterKey: true,
    requireUserKeys: {
        objectId: {
            options: "ABCD1234", // dummy id
            error: "Unauthorized"
        }
    }
});

If I now make a request as the logged in user with the objectId "ABCD1234" I get the error message "Unauthorized", so the validation does not work as intended.

How do you implement user restriction correctly for Cloud functions? Thanks for you help.

2

There are 2 answers

2
Davi Macêdo On

Since you added the validateMasterKey: true option, the cloud code function will run only when passing the master key, regardless of the logged in user. In fact, you should either use validateMasterKey option or requireUserKeys option. It does not make sense to use both of them at the same time.

0
LulzCow On

I haven't tried to use requireUserKeys before, but you could do something like this:

Parse.Cloud.define("hello", async (request) => {
    const authorizedUsers = ["ABCD1234"];
    if(authorizedUsers.indexOf(request.user?.id) == -1) throw "Unauthorized";

    //if you need to do any work that requires masterkey, you can always use the {useMasterKey: true} parameter with your Parse request
    return "Hi " + request.params.name;
 }
});