Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Firebase Firestore, is there any way to pass info to the Security Rules which is not part of the path?

I would like to send some info to Firestore database (Firebase), preferably in key-value pairs (but not necessarily), so that it can use it to evaluate access in their rules (both when reading and writing).

However, I don't want this info to be part of the path.

For example, suppose I had some passParameters method:

DocumentReference docRef = 
      db.collection("cities")
        .document("SF")
        .passParameters("abc", 123);

Then I could access this info when writing rules, like so:

service cloud.firestore {
  match /databases/{database}/documents/cities/SF/ {
    allow read, write: if request.parameters.abc == 123;
  }
}

Please note, the above is just an example. Real-life uses cases are more complicated. In other words, don't pay too much attention to the example itself, but answer the more generic question: Is there any way to pass info to the Security Rules which is not part of the path?

like image 748
MarcG Avatar asked Nov 26 '22 01:11

MarcG


1 Answers

You can send such parameters using custom tokens. Include those values as claims in the custom token, and use that token in your client when sending request to firestore (or signin).

This link explains how to- 1) create custom tokens, 2) include custom claims in those tokens, and 3) access those claims in the security rules.

You can have a cloud function to generate that custom token with custom claims for a specific user.

If the information you want to pass to firebase as parameter changes frequently, then this is going to be a cloud function call everytime you want to change the parameter value you are passing- so a bit costly. But if parameter tend to change less frequently (like- some role or special privilege that the user have), then this solution should work perfect and that's one of the primary benefits of custom token.

Even though it is not as simple as your example expectation snippet, still this I believe is one way to achieve what you want.

like image 156
AsifM Avatar answered Dec 04 '22 11:12

AsifM