Veselin Ivanov
Veselin Ivanov

Reputation: 35

Firestore rules validate query field value

I have collection of users and every user can search for others by their publicId

query(
 collection(db, "users"),
 where("publicId", "==", "..."),
 limit(1)
);

and I want to allow users to regenerate their `publicId"s so others won't be able to find them by the old ones.

The problem is that if someone finds a user once and get their doc id they could potentially get the user by that doc("users", "docId") regardless of their "publicId".

I tried to use request.query.publicId == resource.data.publicId, but query seems to only provide limit, offset and orderBy.

Is there a different way to access the query field value or a different way to mitigate the issue?

Upvotes: 1

Views: 67

Answers (1)

Dharmaraj
Dharmaraj

Reputation: 50830

For the public profile, it might be best to create another collection e.g. "public_users" where the document ID is user's publicId. So when a user regenerates their ID, you can just create another document with new publicId and then delete the previous one.

Do not store a reference to user's UID in this document if you want to keep that a secret. Instead, store this public ID in the "users" collection so that can be read by user only.

Alternatively, you can make your requests through a Cloud Function and block direct requests to Firestore. So there's no way anyone can query by user ID.


For the main collection, you can add a rule that allows users to write their own document only like this:

match /users/{userId} {
  allow write: if request.auth.uid == userId;
}

Upvotes: 2

Related Questions