Search code examples
firebasegoogle-cloud-firestorefirebase-authenticationfirebase-security

How to manage Firebase database security rules for Sign In for the first time when there is no user registered yet?


This is my database Rules:

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 /user/{userId} {
      allow read, write: if request.auth.uid != null; 
    }
    
    match /user/{userId} {
      allow create, read, write, update, delete: if request.auth.uid == userId;
    }
    
    match /{document=**} {
      allow create, read, write, update, delete: if request.auth.uid != null;
    }
  }
}

As you can see user must have to get an auth.uid to get access into the documents of my database.

match /{document=**} {
  allow create, read, write, update, delete: if request.auth.uid != null;
}

But the problem is when I have no user registered on my Authentication (And in Document /user/{userId}) and somebody try to sign in, I can not get any response for the limitation of permission. How should I set my security rules where I can check if a user actually exists or not in Sign In process?

P.S: It's working perfectly if I have at least one user registered on my auth.


Solution

  • With the suggestion of Doug Stevenson, I removed request.auth.uid from /user/{userId} and erase read from same node on the next check and it is working.
    Thanks a lot.

    Full answer is:

    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 /user/{userId} {
          allow read; 
        }
    
        match /user/{userId} {
          allow create, write, update, delete: if request.auth.uid == userId;
        }
    
        match /{document=**} {
          allow create, read, write, update, delete: if request.auth.uid != null;
        }
      }
    }