0

In firestore rules, I have allowed read access to unauthorized users in order to check for username uniqueness before allowing a user to sign up. However, this change has caused my Firebase database to have low security since any user can read my entire database. How can I grant unauthorized users to only have read access to username variables in my "User" collection in firestore to cross check their desired username with existing usernames? I want to guarantee my security is not compromised.

All user data is in my Collection called "User" that contains all user data pertaining to a specific user ID. I also have 6 other collections (Event, Match, Recent, Messages, Typing, Like) in my database that I do not want any unauthorized users to read or write to.

Full firestore database

I pass the desired username as variable "field" to this function to check username availability:

func checkUsername(field: String, completion: @escaping (Bool) -> Void) {
        print("ok")
        var query: Query!
        print(field)
        query = FirebaseReference(.User).whereField(kUSERNAME, isEqualTo: field)
        if query != nil {
            
            query.getDocuments { (snapShot, error) in
                if let err = error {
                    print("Error getting document: \(err)")
                }
                
                guard let snapshot = snapShot else
                {
                    print("empty snapshot")
                    return
                }
               
                if !snapshot.isEmpty {
                    print("not empty")
                    for document in snapshot.documents  {
                        if document.data()["username"] != nil {
                            completion(true)
                        }
                    }
                
                    
                } else {
                    print("empty snapshot")
                    completion(false)
                }
                
            }
            
        } else {
            completion(false)
        }
        
  
        
    }

Firestore Rules Database - User Collection

My current rules are working, but my security is compromised. I want to a way for this to work without compromising security.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
fun lab
  • 29
  • 3

1 Answers1

0

Firebase security rules provides/deny access on a document level. There is no way to provide access to only specific fields within each document.

To securely enforce unique usernames, you'll need to introduce an additional collection that uses the usernames as keys, and typically only has the UID of the user who claimed that name as their only field.

On this collection you can then provide granular access, i.e. only allow get on a specific document and not list (nor read) of all documents in the collection.

For more on this, see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807