dynamic path in firestore security rules

Viewed 267

I have the following setup

collection  document  collection  document
'users'     userId    'test_*'    'results'

A user has the possibility to do the test several times this is why the subcollection could be test_1 or test_12 etc. The number of the latest test ist stored in

/databases/$(database)/documents/user/$(userId)/settings/sharing).data.number_of_tests

The value could be for example 3 (if the user did the test 3 times) which means the path in the firestore rules should look the following:

/users/{userId}/test_3/results

Is is it possible to change only a part of the description for the path, in my case only the number behind the "test_" according to the feedback from the database which I get with get(...)?

Currently I tried the following but it does not work..

match /users/{userId}/test_{cycle}/results {
      allow read: if cycle == string(get(/databases/$(database)/documents/user/$(userId)/settings/sharing).data.number_of_tests)
    }

Does anybody know wether this is possible and how i can make it work?

Thanks!!

1 Answers

I found myself a solution. I call a function to extract the data from my database, put together the sting and then compare the return value with the path.

  // FUNCTIONS AREA
    function getNumber(userId) {
      let number = string(get(/databases/$(database)/documents/user/$(userId)/settings/sharing).data.number_of_tests);
      let name = "test_";
      let returnValue = name+number;
      return returnValue
    }


//CALL THE FUNCTION
    match /users/{userId}/{test}/results {
      allow read: if test== getNumber(userId);
    }
Related