to create a new user (via email authentication) I have to allow everything in firestore, is there a better way?
match /users/{userId=**} {
allow get, list;
}
Code: I check whether the name is already taken
Future<bool> doesNameAlreadyExist(String name) async {
final QuerySnapshot result = await FirebaseFirestore.instance
.collection('users')
.where('name', isEqualTo: name)
.limit(1)
.get();
final List<DocumentSnapshot> documents = result.docs;
return documents.length == 1;
}
authentication then takes place later when the user presses the login button:
final auth = Provider.of(context)!.auth!;
String uid = await auth.createUserWithEmailAndPassword(
emailController.text,
passwordController.text,
nameController.text,
);
CodePudding user response:
As mentioned in the Answer:
Enforcing uniqueness is only possible by creating an extra collection. In your current structure, to know if a username is unique, you will need to read each document. This is incredibly inefficient, and on top of that it isn't possible in security rules, since they can only read a few documents per rule.
The trick is to create an extra collection of usernames, where you also have a document for each user, but now the key/ID of each document is the username. With such a collection, you can check for the existence of a certain document, which is a primitive operation in the security rules.
For information you can check some similar scenarios - case_1 , case_2 and case_3.