Search code examples
iosparse-platformmbaas

How to save user that is not logged in with Parse?


I am working on an app that requires being able to search for partners to play with. Obviously, saving for the user is not an issue, but I'm not sure what would be the best way to modify the data for the other user. Perhaps sending a message to the other user which automatically gets read upon login and adds the relation status?

Here's what I have - it finds a random player from all the players also searching for a game and adds them to the "partners" relation. Now how would I have this happen for the other user as well?:

- (IBAction)searchForPlayer:(id)sender {


     [self.currentUser setObject:@0 forKey:@"searching"];

    PFQuery *findPotential = [PFQuery queryWithClassName:@"_User"];
    [findPotential whereKey:@"searching" equalTo:@1];
    [findPotential findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        int partnerNum = arc4random_uniform(objects.count);
        PFUser *newPartner = [objects objectAtIndex:partnerNum];

        if(error){
            NSLog(@"Error!");
        }

        else {

            if (objects.count == 0|| [newPartner.objectId isEqualToString:self.currentUser.objectId]) {
                NSLog(@"None found");
                [self.currentUser setObject:@1 forKey:@"searching"];
            }

            else {

                PFRelation *partners = [self.currentUser relationForKey:@"partners"];
                [partners addObject:newPartner];
                NSLog(@"Partner is: %@", newPartner.username);
                [self.currentUser setObject:@0 forKey:@"searching"];
            }
        }
    }];

[self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if(error){
        NSLog(@"Error!");
    }
  }];
}

Solution

  • You don't ever want to do something like this client-side. For security purposes, a User can't alter another user. Use Cloud Code. Call a function, and in that function verify you really want to do this, and then use the Master Key to query for and alter other objects.

    You can mostly just convert your Objective-C query/example to JavaScript, put it inside a Cloud Function that accepts a few parameters, and put this at the top:

    Parse.Cloud.useMasterKey();
    

    Or, you can provide the master key individually to specific methods, such as:

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

    Read up on the Cloud Code docs here: https://parse.com/docs/cloud_code_guide