【发布时间】:2020-07-04 16:14:37
【问题描述】:
我的应用程序中有一个 recyclerview,它通过 get 检索集合中的所有文档。每个文档都包含创建它的人的 uid。我想实现一个安全规则,在该规则中,您只检索与所有者的 uid 匹配的文档。它看起来很简单,但我无法让它工作。
数据库有这样的结构
cars
|
|-documentA
|-documentB
|-documentC
每个文档:
documentA
|
|
|-fieldA: aaa
|-fieldB: bbb
|-userId: aklsjdaosjfpasf
firestore 的安全规则
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{cars=**}/{carId} {
allow read: if request.auth.uid == resource.data.userId;
allow write: if request.auth.uid != null;
}
}
}
编辑 查询:
query = firestore.collection("cars").limit(10L)
用于查询 recyclerview 的 Firestore 适配器
public abstract class FirestoreAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH> {
private static final String TAG = "Firestore Adapter";
private Query mQuery;
private ListenerRegistration mRegistration;
private ArrayList<DocumentSnapshot> mSnapshots = new ArrayList<>();
public FirestoreAdapter(Query query) {
mQuery = query;
}
public void startListening() {
// TODO(developer): Implement
}
public void stopListening() {
if (mRegistration != null) {
mRegistration.remove();
mRegistration = null;
}
mSnapshots.clear();
notifyDataSetChanged();
}
public void setQuery(Query query) {
// Stop listening
stopListening();
// Clear existing data
mSnapshots.clear();
notifyDataSetChanged();
// Listen to new query
mQuery = query;
startListening();
}
@Override
public int getItemCount() {
return mSnapshots.size();
}
protected DocumentSnapshot getSnapshot(int index) {
return mSnapshots.get(index);
}
protected void onError(FirebaseFirestoreException e) {};
protected void onDataChanged() {}
}
【问题讨论】:
-
究竟是什么不符合您的安全规则?同样只允许读取匹配的用户但允许写入所有经过身份验证的用户似乎是错误的
-
我无法从我的 recyclerview 中检索任何内容,它给了我一个错误,我没有足够的权限。允许所有用户在应用程序中进行身份验证的想法是因为每个人都可以注册汽车,但只有车主才能看到。
-
这种做法是错误的,如果你允许某人写一个文件,他们就可以阅读它。您可能想使用
allow create而不是allow write -
好的,有道理。我就是这样改变的。了解创建和写入的区别。
-
您能否在问题中添加用于获取数据的查询?
标签: firebase google-cloud-firestore firebase-security