Search code examples
realmrealm-mobile-platformrealm-js

Realm JS get records owned by a user with admin user


I am developing an app where I'm using Realm JS with fine graded permissions. I think this is a really huge feature, and it is way better than using separeted realms. I succesfully implemented record level permission, so I have one table with different records owned by different users. Now what I am trying to do is to retrieve, server side and with admin credentials, all the records of a given table owned by a specific user. Is that possible? I couldn't find anything helpful in the docs


Solution

  • Option 1 - filter by user

    This option depends on how you have your user roles setup and how you apply them to the objects. If you are using the default __User role created for each user and creating your permissions with that, providing you have the userId, you can query the permissions on the object to find the ones by the specific user.

    e.g. get the first permission on the object

    let permission = object.permissions[0];

    The role name will be:

    let roleName = permission.role.name

    roleName will be in the format '__User:Id'

    So, in theory you could query it as so (untested):

    realm.objects('YourObject').filtered(permissions.role.name == '__User:${id}');.

    Option 2 - login as the user

    The other option, and what I do, is login as the user. I use JWT Auth so I don't need a password. I generate a JWT token for the user and login. I can then open the realm as that user and only that user's records will be available.