用户如何在 Cloud Firestore 中只能看到自己的数据?

问题描述 投票:0回答:1

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

我想做的是如何让用户只能看到自己的数据。所以我不希望用户看到彼此的数据。我只是希望每个用户都能看到自己添加的数据。我认为我需要更改 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
    }
  }
}

My cloud firestore screenshot

我保存用户邮箱、注释标题...等。到我共享的数据库;

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个回答
4
投票

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

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

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

service cloud.firestore {
  match /databases/{database}/documents {
    // Allow public read access, but only content owners can write
    match /some_collection/{documents=**} {
      // Allow reads
      // Allow creation if the current user owns the new document
      allow read, create: if request.auth.uid == request.resource.data.author_uid;
      // Allow updates by the owner, and prevent change of ownership
      allow update: if request.auth.uid == request.resource.data.author_uid
                    && request.auth.uid == resource.data.author_uid;
      // Allow deletion if the current user owns the existing document
      allow delete: if request.auth.uid == resource.data.author_uid;
    }
  }
}

此示例直接来自“仅保护内容所有者访问”的文档,因此我建议阅读该文档以了解更多详细信息。

© www.soinside.com 2019 - 2024. All rights reserved.