Reputation: 3804
I am new to Firestore and I'm trying to setup simple security rules so that only someone who is signed in can create a new database entry and that users can only read and write their own entries.
service cloud.firestore {
match /databases/{database}/documents {
match /Users/{userID} {
// Can only create a new entry if signed in with a uid.
allow create: if request.auth.uid != null;
// Can only update an entry if signed in with uid and changing own information (saved under uid)
allow update: if request.auth.uid != null &&
userID == request.auth.uid;
// Can only read (get/list) an entry if signed in with uid and reading own information (saved under uid)
allow read: if request.auth.uid != null &&
resource.data.userID == request.auth.uid;
}
} }
The create new entry case works fine, but I wonder if this is secure enough.
For updating and reading, I also want to check that the user is updating/reading their own entry. The document name is the uid (in other words UserID) from Firebase so simply checking that request.auth.uid is the same should do the trick, but something is off in the way I'm writing it. The call gets blocked and when I run it in the simulator I get the error: Missing or insufficient permissions. I can't figure out after reviewing the documentation and this tutorial video.
Upvotes: 0
Views: 95
Reputation: 1274
Something like below should be sufficient for your situation:
// True if the user is signed in or the requested data is 'public'
function signedInOrPublic() {
return request.auth.uid != null || resource.data.visibility == 'public';
}
// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /users/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if signedInOrPublic();
}
Upvotes: 1