Home > Software engineering >  Is it possible to prevent send custom id by rules in firebase
Is it possible to prevent send custom id by rules in firebase

Time:10-25

Is there any way to prevent user send custom id for newly created document? For example

This operation create's new document with id "8pqLuAc6BXCVRF7SB6xT"

db.collection("users").add({foo : 1})

And in my application i always want to have id generate by firebase sdk not by user

because as we know user can hack app and trigger operation like this

db.collection("users").doc('CUSTOM_ID').set({foo : 1})

After this operation id will be "CUSTOM_ID" instead generated by SDK like '8pqLuAc6BXCVRF7SB6xT'

So question is how to write rule to ensure me that id is generated from sdk

CodePudding user response:

Update following your clarification:

It is not possible with Security Rules to avoid a user specifying the ID of a document when it is created.

Even if the code in your front end only uses the add() method, one can write his own code and use the doc() method to write to your DB (as soon as he gets the Firebase configuration object, which is easy).

One possibility would be to write to Firestore via a Cloud Function, but this has some drawbacks see this article.


Original answer:

It is not crystal clear what you mean by a "custom id" but I understand that you probably want a given user to be able to create a document in the users collection only if this document ID is corresponding to his user uid (from the Auth service)

The following Security Rule should the trick:

service cloud.firestore {
  match /databases/{database}/documents {
    // Make sure the uid of the requesting user matches name of the user
    // document. The wildcard expression {userId} makes the userId variable
    // available in rules.
    match /users/{userId} {
      allow create: if request.auth != null && request.auth.uid == userId;
      // ...
    }
  }
}
  • Related