【问题标题】:How users can only see their own data in Cloud Firestore?用户如何只能在 Cloud Firestore 中查看自己的数据?
【发布时间】:2021-02-22 08:20:44
【问题描述】:

我正在使用 Kotlin 构建一个应用程序。在app中,用户可以注册并登录。用户登录后,用户添加一些文字和图片,这些数据成功添加到firebase云存储中,并以列表的形式显示在app中。但是,在该应用上注册的任何人都可以访问此列表。

我想做的是用户只能看到自己的数据。所以我不希望用户看到彼此的数据。我只希望每个用户都能看到他们自己添加的数据。我认为我需要更改 Firebase Cloud Strore 规则,并且我认为 userId 必须等于 documentId 才能做到。但是我该怎么做呢?

我是新手,谢谢!

Cloud Firestore 规则;

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow only authenticated content owners access
    match /Notes/{userId}/{documents=**} {
      allow read, write: if request.auth != null && request.auth.uid ==userId
    }
  }
}

我保存了 useremail、noteTitle ...等。到我共享的数据库;

val noteMapElse = hashMapOf<String, Any>()

            noteMapElse.put("userEmail", auth.currentUser!!.email.toString())
            noteMapElse.put("noteTitle", titleText.text.toString())
            noteMapElse.put("yourNote", noteText.text.toString())
            noteMapElse.put("date", Timestamp.now())



            //UUID -> Image Name

            val uuid = UUID.randomUUID()
            val imageName = "$uuid.jpg"

            val storage = FirebaseStorage.getInstance()
            val reference = storage.reference
            val imagesReference = reference.child("images").child(imageName)

            imagesReference.putFile(selectedPicture!!).addOnSuccessListener { taskSnapshot ->

                // take the picture link to save the database

                val uploadedPictureReference =
                    FirebaseStorage.getInstance().reference.child("images").child(imageName)
                uploadedPictureReference.downloadUrl.addOnSuccessListener { uri ->
                    val downloadUrl = uri.toString()
                    println(downloadUrl)

                    noteMapElse.put("downloadUrl", downloadUrl)

                    db.collection("Notes").add(noteMapElse).addOnCompleteListener { task ->
                        if (task.isComplete && task.isSuccessful) {

                            finish()
                        }


                    }.addOnFailureListener { exception ->

                        Toast.makeText(
                            applicationContext,
                            exception.localizedMessage?.toString(),
                            Toast.LENGTH_LONG
                        ).show()

                    }

                }


            }


        }

这也是我的登录和注册活动;

fun signIn (view: View) {

        auth.signInWithEmailAndPassword(mailText.text.toString(), passwordText.text.toString())
            .addOnCompleteListener { task ->

                if (task.isSuccessful) {

                    Toast.makeText(applicationContext, "Welcome : ${auth.currentUser?.email.toString()}",
                        Toast.LENGTH_LONG).show()
                    val intent = Intent(applicationContext, ListViewActivity::class.java)
                    startActivity(intent)
                    finish()
                }

            }.addOnFailureListener { exception ->
                Toast.makeText(
                    applicationContext,
                    exception.localizedMessage?.toString(),
                    Toast.LENGTH_LONG
                ).show()

            }

    }


    fun signUp (view: View) {

        val email = mailText.text.toString()
        val password = passwordText.text.toString()


        auth.createUserWithEmailAndPassword(email,password).addOnCompleteListener {

            if (it.isSuccessful) {

                Toast.makeText(applicationContext, "Your Account Has Been Created Successfully", Toast.LENGTH_LONG).show()

                val intent = Intent(applicationContext, ListViewActivity::class.java)
                startActivity(intent)

                finish()

            }

        }.addOnFailureListener { exception ->

            if (exception != null ) {

                Toast.makeText(applicationContext,exception.localizedMessage.toString(),Toast.LENGTH_LONG).show()

            }

        }


    }

}

【问题讨论】:

    标签: android firebase google-cloud-firestore firebase-security


    【解决方案1】:

    为确保用户只能看到自己的笔记,您需要有某种方法来识别每个文档所属的用户。有两种常见的方法可以做到这一点:

    1. 将特定用户的所有笔记存储在包含他们自己的 UID 的路径中。
    2. 在每个文档中存储所有者的 UID。

    从屏幕截图看来,您遇到了第一种情况,因为 UID 似乎被用作文档 ID。在这种情况下,您可以使用以下方法保护它:

    service cloud.firestore {
      match /databases/{database}/documents {
        // Allow only authenticated content owners access
        match /some_collection/{userId}/{documents=**} {
          allow read, write: if request.auth != null && request.auth.uid == userId
        }
      }
    }
    

    此示例直接来自 securing content-owner only access 上的文档,因此我建议您阅读该文档以了解更多详细信息。

    【讨论】:

    • 我尝试了你写的代码,然后我在我的应用程序中按下了保存按钮,它没有将数据保存在云存储中并且 - “权限被拒绝或权限不足” - 出现吐司消息。跨度>
    • 如果没有看到代码和更新规则,就不可能说出为什么会这样。
    • 正如弗兰克评论的那样,我认为您应该向我们提供更多关于您如何构建您的 firestore 的 security rules 的信息。此代码不能开箱即用,您需要将其调整为您的实际代码。请阅读Firebsae Rule Documentation,并通过一些示例告诉我们您如何尝试实施您的规则
    • @FrankvanPuffelen 我编辑了这个问题。你能检查一下吗?谢谢
    • 我修复了它但没有用。它不能解决我的问题。但是感谢@FrankvanPuffelen 的示例
    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2019-09-21
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    相关资源
    最近更新 更多