Basic Realm Sync Permissions

Can someone pretty please help guide me to the correct sync permissions for the most basic Realm Sync app? I want an authenticated user to be able to read and write their own data. That’s it. There’s no public data. No other rules.

The defaults that come with the Realm + Swift template are the following:

{
  "%%partition": "%%user.id"
}

And the partition key is also the default, set to " _partition, string, required".

When I try my basic test app, the console spits out the error:
“user does not have permission to sync on partition (ProtocolErrorCode=206)”

Setting both fields to “true” allows me to sync, but this is insecure, correct?

I also tried:

{
  "%%user.id": "%%partition"
}

Which I found in the define sync rules documentation, but no luck there either.

Thanks a lot.

What is the value of _partition in the document that you’re attempting to sync? Does it match the id of the user?

If you believe they match, then you could debug things by delegating the check to a function…

Replace your “read” and “write” rules with:

{
  "%%true": {
    "%function": {
      "arguments": [
        "%%partition"
      ],
      "name": "canReadWritePartition"
    }
  }
}

Create a Realm Function named canReadWritePartition that looks like this:

exports = function(partition) {
    console.log(`Checking if the partition ${partition} matches the user id (${context.user.id})`);
    return partition === context.user.id;
};

You can then check the Realm logs to confirm what _partition and user.id were set to (and why they don’t match).

1 Like

Thank you for the reply Andrew. I’m tried your suggestion (and I should reiterate that I’m just going off the defaults for a fresh app). The value of _partition is set to

user=611fb02e79c8aaa253621e06

The console spits out:

Checking if the partition user=611fb02e79c8aaa253621e06 matches the user id (611fb02e79c8aaa253621e06)

I also tried:

{
“%%partition”: “user=%%user.id”
}

But no luck :slightly_frowning_face:.

OK - that console output is useful. The doc’s partition is user=611fb02e79c8aaa253621e06, whereas the user id is 611fb02e79c8aaa253621e06.

Your updated expression is a good idea, but I’m not sure if there’s a JSON expression syntax that will concatenate "user=" and "%%user.id".

tbh, I almost always delegate the check to a Realm Function rather than trying to get clever in the JSON expression. To solve it that way, keep the JSON expressions as I described but update the check in the function to:

return partition === "user=${context.user.id}";
1 Like

Great, this works. For future reference, the complete function to allow the user read/write access to their own Realm data is:

exports = function(partition) {
    return partition === `user=${context.user.id}`;
};
1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.