Reputation: 68
I want to create new rules for my client - one client can create one document in collection.
match /Users/{userId} {
allow update, delete: if request.resource.data.uid == uid;
allow create: if
request.data.uid != request.resource.data.uid;
if request uid == request.resource.data.uid; he cannot.
Upvotes: 1
Views: 140
Reputation: 598728
If you want each user to only be able to create a single document, that is easiest if you use the user's UID as the document ID. In JavaScript that'd be something like this:
import { doc, setDoc } from "firebase/firestore";
import { getAuth } from "firebase/auth";
const user = getAuth().currentUser;
await setDoc(doc(db, "Users", user.uid), {
displayName: user.displayName,
});
You can then enforce this content-owner only access in security rules with:
service cloud.firestore {
match /databases/{database}/documents {
// Allow only authenticated content owners access
match /Users/{userId}/{documents=**} {
allow write: if request.auth != null && request.auth.uid == userId
}
}
}
The main difference with your approach is that we don't check the data of the document, but instead check the document ID (which we set to the UID in our code) to the UID on the request.
Upvotes: 2