android - 如何允许用户从 Firebase 中删除他们的帖子?
问题描述
我设置了一个回收视图,其中填充了来自 Firebase 的用户帖子。我想实现一个功能,允许用户删除自己的帖子(类似于 Facebook 或 Instagram)。到目前为止,我已经编写了一些允许删除帖子的代码,但任何用户都可以删除它。
//This is how my database is set up
Post
-LlISwmjd0pBXzkNHJGW (random push id)
desc: "Used textbook"
id: "Zk32WqxcCHbR1op6j9inFudFJF23"
image: "image link"
name: "user name"
profileimage: "profile image"
//This method allows a post to be removed
//Creates popup and allows user to delete from RecycleView
public void openOptionMenu(View v, final int position) {
PopupMenu popup = new PopupMenu(v.getContext(), v);
popup.getMenuInflater().inflate(R.menu.options_menu, popup.getMenu());
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu1:
Toast.makeText(getApplicationContext(), "Edit clicked", Toast.LENGTH_SHORT).show();
return true;
case R.id.menu2:
FirebaseDatabase.getInstance().getReference().child("Post").child(randomPostKeyId).removeValue();
postList.remove(position);
adapter.notifyDataSetChanged();
return true;
default:
//default intent
return true;
}
}
});
popup.show();
}
解决方案
您可以设置 Firebase 安全规则,以便只有所有者才能修改/删除帖子。假设每个帖子都有一个包含创建它的用户的用户 ID 的属性,如果键的名称是,ownerId
那么它看起来像这样:
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"Post": {
"${postId}": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "root.child('Post').child(postId).child('ownerId').val() == auth.uid"
}
}
}
}
查看https://firebase.google.com/docs/rules以获取完整的 ddocumentation。
推荐阅读
- php - 如何在 Drupal 7 中使用 entity_save 函数插入数据?
- javascript - 在axios中检测xhr.status === 0
- mysql - MYSQL:带有二进制数据的 JSON_OBJECT
- spring - Spring Cache 通过 cacheName 配置禁用缓存
- r - 在 R Shiny 中同时对用户上传的文件运行多个渲染函数
- javascript - javascript:使用索引作为参数更新 Array() 中的属性值
- ios - iOS 添加 GMSPolylines 与有线现象结果
- javascript - Konva 组 X&Y 与形状 X&Y 不同
- java - ZXing BinaryBitmap 转 BufferedImage
- arrays - 从 R 中的另一个 3D 数组填充 3D 数组的最快方法