【发布时间】: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