Search code examples
androidfirebasegoogle-cloud-firestorefirebase-security

What should be the Firestore security settings for Android app?


I just created my first Android app in Kotlin with FIrestore as the database and I used Phone Authentication as well. When I created the database, I used Test Mode and now I want to upload my app to Google Play so that the public can start using my app. What should be the security settings for the Firestore that I should consider changing? Please give some advice on this.

Currently, this is what is under the Rules tab.

    rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if
          request.time < timestamp.date(2021, 8, 29);
    }
  }
}

Solution

  • From what I understand from the example in comments, you have 7 collections (example) A, B, C, P, Q, Y and Z.

    Collection Can be accessed by
    A, B, C Certain users
    P, Q Users authenticated by Phone auth
    Y, Z Certain users
    rules_version = '2';
    service cloud.firestore {
      match /databases/{database}/documents {
        match /A/{docId} {
          allow read, write: if isCertainUser();
        }
        // Same rule for B and C
    
        match /P/{docId} {
          allow read, write: if request.auth != null && request.auth.token.firebase.sign_in_provider == "phone";
        }
        // Same rule for Q
        // Checks if user is logged in by Phone auth
    
        match /Y/{docId} {
          allow read, write: if isCertainUser();
        }
        // Same rule for Z
      }
    }
    

    You would have to write a function isCertainUser for the rule to work. Now there are multiple ways you can specify a user to have access. For example, you could add an admin custom claim or store documents of users who can access the collection in a separate collection and check if the document of user who is requesting data is present in that whitelisted collection.

    match /A/{docId} {
      allow read: if request.auth != null && exists(/databases/$(database)/documents/whitelisted/$(request.auth.uid));
    }
    

    This rule will allow users to read data in collection A only if a document with the user's UID as document key exists in the collection "whitelisted".

    References:

    Writing conditions for Cloud Firestore Security Rules

    Interface for request.auth