首页 > 解决方案 > 如何允许用户从 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();
    }

标签: androidfirebase

解决方案


您可以设置 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。


推荐阅读