While a new user register I have to check if the desired username is already given. Therefor I check the username with the following query:
result = await FirebaseFirestore.instance
.collection('user')
.where('usernameName', isEqualTo: usernameEditController.text)
.get();
userNameExists = result.docs.isEmpty;
Code works fine and give back the right boolean if the username is already given.
Now there's a problem with the firebase rules. Because I ask for the username (code above) with being loged in I have to set the firebase firestore rules to:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
}
}
But with these rules everyone is allowed to read and write. Is there a possibility to check the username without changing the rules or with another query for the username?
You can allow all users to check the "users" collection even without authenticating. This is not an optimal solution because anyone will be able to read the user's collection.
Another thing you can do is to have another collection called "usernames", which you will add new users to, but the only data that will be there will be the username.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{collectionName}/{documentId} {
allow read : if (collectionName == "users" || request.auth != null);
allow write : if request.auth != null;
}
}
}