1

In the Firestore docs, one recommended way of writing security rules is

service cloud.firestore {
  match /databases/{database}/documents {
    match /users/{userId} {
      allow read, update, delete: if request.auth.uid == userId;
      allow create: if request.auth.uid != null;
    }
  }
}

However, when I create a user the userID is different from the auth.uid (both are random strings, but totally random).

How do I make them match automatically when a new user is created?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Richard Reis
  • 219
  • 2
  • 10

1 Answers1

1

The rule you're showing suggests that the ID of the document should match the UID of the user as obtained by Firebase Authentication. This is standard practice. If your code doesn't also write documents this, then the rule won't work as you'd expect. So, you get the UID of the user and use that as the ID of the document.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • But I never specified what I wanted the document’s ID to be (it was generated automatically) is there a way on Firebase to always make it the same as the auth ID? – Richard Reis Mar 25 '19 at 04:31
  • 2
    Yes, get the UID of the user from Firebase Auth and use that as the ID of the document. – Doug Stevenson Mar 25 '19 at 04:32
  • How do you do that in code? Is it in `Auth.auth().createUser()` or `firestoreUsersCollection.addDocument()` – Richard Reis Mar 25 '19 at 05:45
  • 1
    In my answer, I linked to an example of getting the UI that I found from a search. – Doug Stevenson Mar 25 '19 at 05:45
  • That explains how to get the UID but not how to set it when creating the user (the user has to be logged in with the link you provided, but I want to automatically assign that UID when the user is created at registration, before login) – Richard Reis Mar 25 '19 at 06:07
  • It is not automatic. You have to write code to specify the name of the document, which will be the UID of the user. Please read the documentation. https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document – Doug Stevenson Mar 25 '19 at 15:39