I have a deletePost
function that will delete a post but currently, any user can delete any other user's posts.
I added a check but now the user can't delete their own or anyone else's posts.
Future<void> deletePost(String postId) async {
try {
if (FirebaseAuth.instance.currentUser!.uid == _firestore.collection('posts').doc('uid').toString()) {
await _firestore.collection('posts').doc(postId).delete();
}
} catch (err) {
print(err.toString());
}
}
I want to be able to do a check to see if the currentUser
's uid
is the post
user's uid
and then delete else for it to do nothing.
Rules added:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{document=**} {
allow read, write;
delete: if request.auth.uid == userId
}
}
}
I now receive [Firestore]: Listen for Query(target=Query(posts/*******-****-****-*******/comments order by __name__);limitType=LIMIT_TO_FIRST) failed: Status{code=PERMISSION_DENIED, description=Missing or insufficient permissions., cause=null}
when accessing the posts feed.
Assuming I've messed up the rules for testing.
Solution:
InkWell(
onTap: () async {
if (FirebaseAuth
.instance.currentUser!.uid == widget.snap['uid']) {
FirestoreMethods().deletePost(
widget.snap['postId'],
);
Navigator.of(context).pop(context);
}
},
Rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write;
}
match /users/{userId}/{document=**} {
allow delete: if request.auth.uid == userId
}
}
}
CodePudding user response:
You have to set up some rules for this check on the firestore side:
The first case: You have to put your posts collection inside users collection in this case this rule will work
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{userId}/{document=**} {
allow delete: if request.auth.uid == userId
}
}
}
The second case: If your posts and users are separate collections, in this case, you can configure this rule for security purposes:
match /posts/{document=**} {
allow read, delete, create: if request.auth != null
}
In post collection, you have to place a parameter which is called userId
. But in your UI, you have to put a check which will check whether this post belongs to the user.
postDocs[index]['userId'] == futureSnapshot.data.uid