I'm trying allow authenticated users who has associated document in firestore databases /User
collection (i.e. a document with users uid
as its documentId
) to view, edit or delete their own documents. Also, authenticated users who doesn't have their own associated document can create a document for them. A user can only have one document linked to them.
Being new to firestore, I've tried many times to implement it, but to no avail. All it says is "Error creating user: Missing or insufficient permissions".
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /Persons/{document=**} {
allow read: if request.auth.uid != null;
}
match /users/{userId} {
//a user can have only one associated document
allow read, update, delete: if (request.auth.uid == userId && request.auth.uid != null);
//create document of new user who already doesn't have an associated document.
allow create: if (request.auth.uid != null && exists(/databases/$(database)/documents/Users/$(request.auth.uid))==false);
}
match /users{ //backup to check if earlier create rule had mistake
allow create: if request.auth.uid != null && !exists(/databases/$(database)/documents/Users/$(request.auth.uid));
}
}
}
The reactJS code that tries to to create a new user account and create users own document in /Users
collection:
const SignUp = async () => {
try {
const userCredential = await createUserWithEmailAndPassword(
auth,
email,
password
);
// Get the newly created user's UID
const { uid } = userCredential.user;
console.log(userCredential);
// Write user data to Firestore under the `/users` collection
await setDoc(doc(db, "Users", uid), {
name: username,
email: email,
uid: uid,
cgpa: 3.56,
});
console.log("User created successfully");
} catch (error) {
console.error(`Error creating user!`);
}
};
Your code and your rule don't match paths.
Your code attempts to write to /Users/{userId}
, but your rule is matching /users/{userId}
. Note the difference in case. Firestore is entirely case sensitive for all operations.