When a user registers, a document should be set in Firestore (database/users/${uid}). However, I keep getting a "Missing or insufficient permissions." error.
This is the most relevant security rule
match /users/{documents=**} {
allow read, create, update: if request.auth != null && request.auth.uid == resource.id
}
Another rules I tried implementing was
match /users/{uid=**} {
allow read, create, update: if request.auth != null && request.auth.uid == uid
}
and this is the code that registers the user and sets the document
createUserWithEmailAndPassword(auth, emailInput, passwordInput).then(
(UserCredential) => {
console.log(UserCredential);
uid = UserCredential.user.uid;
sendEmailVerification(auth.currentUser).then(() => {
toast.success(
"Account created and email verification sent! Please check your inbox/spam folder",
{
duration: 10000,
}
);
setDoc(doc(db, "users", uid), {
userSettings: ["example", 0],
});
router.push("/verify");
});
}
);
Why can't I set a document as an authorized user accessing my own user document?
CodePudding user response:
The problem is request.auth.uid == resource.id
. From the documentation,
The
resource
variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document.
But the document does not exists as user has just registered to your application.
Try the following rules instead:
match /users/{userId} {
allow read, create, update: if request.auth != null && request.auth.uid == userId;
}
This rule will ensure that a user can create/read/update a document with their user ID only.
Also do note that the match path is /users/{userId}
and not match /users/{userId=**}
as in your question. The value of userId
would be /userID
and not just userID
if you use the recursive wilcard (=**
) and rule will fail always.
If the rule must be applied for all nested collections, then use the recursive wildcard on the next path segment:
match /users/{userId}/{path=**} {
// ... can still read userId
}