7
votes

I am trying to write a rule for my Firebase users.

My goal is to have a rule to allow write/read in the database for:

  1. anonymous users authentificated through Firebase auth which are temporary anonymous accounts
  2. authenticated users with email and password.

How can I achieve that ?

2

2 Answers

14
votes

In the Firebase Realtime Database, you can give everyone who is signed in access to your entire database with:

{
  "rules": {
    ".read": "auth.uid !== null",
    ".write": "auth.uid !== null"
  }
}

In Cloud Firestore you can accomplish the same with these rules:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

Note that both of these samples come from the Firebase documentation, so I highly recommend that you spend some time studying that.

13
votes

I don't agree with accepted answer. If user is authenticated as Anonymous, he has UID anyway so checking if it is null doesn't solve the problem.

'auth' variable has 'provider' property so all you have to do to check if user is authenticated with email and password or anonymously is this:

{
  "rules": {
    ".read": "auth.provider != 'anonymous'",
    ".write": "auth.provider != 'anonymous'"
  }
}

Here is more from documentation: https://firebase.google.com/docs/reference/security/database#variables