reactjs - 无法获取要显示的客户端数据 [firestore]
问题描述
我的数据库设置为 /clients 并使用 firebase auth 来处理用户。我想让它让用户只能查看、编辑和删除他们创建的客户端数据。当前的 Firestore 安全规则是。
[code]service cloud.firestore {
match /databases/{database}/documents {
// Make sure the uid of the requesting user matches name of the user
// document. The wildcard expression {userId} makes the userId variable
// available in rules.
match /clients/{userId} {
allow read, update, delete: if request.auth.uid == userId;
allow create: if request.auth.uid != null;
}
}
}[/code]
使用此规则,用户可以将新客户端添加到数据库中,但是网站上的客户端不会显示。我有代码设置,以便当用户添加客户端时,它将用户 UID 附加到“userId”下的客户端。显示客户端的代码是
[code]<tbody>
{clients.map(client => (
<tr key={client.id}>
<td>{client.firstName} {client.lastName}</td>
<td>{client.dateCreated}</td>
<td><a href={`tel:${client.phone}`}>{client.phone}</a></td>
<td>
<Link to={`/client/${client.id}`} className="btn btn-secondary btn-sm">
<i className="fas fa-arrow-circle-right"></i> Details
</Link>
</td>
</tr>
))}
</tbody>
[/代码]
我不确定我做错了什么,是安全规则还是我选择如何显示数据?
解决方案
我的理解是你有一个客户集合和一个用户集合。用户可以创建客户端,并且只能查看/编辑/删除他们创建的客户端,对吗?如果是这样,只需添加一个createdBy(可以是任何东西)字段,其中包含创建特定客户端的用户 uid,并检查此字段是否等于您从 auth 对象获得的 uid:
service cloud.firestore {
match /databases/{database}/documents {
match /clients/{clientId} {
// only user who created the client can read/update/delete it
allow read, update, delete: if resource.data.createdBy == request.auth.uid;
// logged user only can create a client
allow create: if request.auth.uid != null;
}
}
}
通配符 {clientId} 只是在这里说“嘿,此规则适用于 clients/ 集合下的任何文档”。借助resource.data对象,您可以获取存储在文档中的数据。
文档中列出了所有内容:https ://firebase.google.com/docs/firestore/security/get-started
推荐阅读
- python - 为什么有些前面带“__”的方法不是私有的?
- python - 将多级索引数据框转换为嵌套字典
- php - 将另一个表中的列值添加为默认常量
- python - Pip 升级到 20 版现在需要 19?
- c# - 如何将正则表达式模式放在另一个正则表达式模式中而不会出现不匹配
- android - Android 在 android Service 中使用 LocalBroadcastManager
- sql - SQL日期查询带括号的区别
- php - 连接 MySQL 数据表中的 2 行的 PHP 下拉菜单
- sprite-kit - 为什么将 SKNode() 分配给变量时会产生无穷无尽的敌人?
- javascript - 为什么 document.body.requestFullscreen() 仅在第一次调用时起作用?