Check if Firestore user exists when rules forbid anybody but the user to read

Viewed 252

I have the following rules set up for the users collection

   match /users/{userId} {
       allow read, write, update: if request.auth != null && request.auth.uid == userId
   }

And I would like to check if a user exists but the above rules won't let me. Should I allow read rights to all logged in users?

   FirebaseFirestore.instance
   .collection('users')
   .where('email', isEqualTo: snap[index]['email'])
   .get()
2 Answers

Try creating a separate collection where you store all the emails, then check if the email exists there or not, and show the right message accordingly. This collection should be able to be accessed by all users authenticated or not.

You can set up the Security Rules to match only if the email field matches the user's email address. There are a couple of things to consider...

  1. Rules are not filters. You must search explicitly for this document
  2. This will not work with phone auth users. You will need to add another rule if you want to handle phone login.
match /users/{userId} {
  allow read: if request.auth != null && request.auth.email == resource.data.email
  allow write: if request.auth != null && request.auth.uid == userId
}
Related