我的数据库设置为/ clients,并使用firebase auth来处理用户。我想这样做,以便用户只能查看,编辑和删除他们创建的客户数据。当前的防火墙安全规则是。
[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}就在这里说“嘿,此规则适用于客户/集合下的任何文档”。借助resource.data对象,您可以获取存储在文档中的数据。
所有内容都列在文档中:https://firebase.google.com/docs/firestore/security/get-started
我能够得到我的结果,但不是通过安全规则。在调整安全规则和我的数据库变量以便将用户id附加到他们添加的数据之后,我尝试了@firebaser建议的规则。我能够在上面提到的规则下创建客户端但是,我无法查看它们,并且在控制台中我得到了“配置文件监听器错误:权限丢失或不足.FirebaseError:缺少权限或权限不足”。
根据错误看起来我必须编辑项目文件夹的节点模块中的一个firebase文件。我不想冒险修改这些文件,因此我没有使用安全规则来过滤数据,而是改变了客户端数据的显示方式。我在.filter
函数之前添加了一个.map
,以便它只显示链接到用户id的客户端。虽然我的安全规则只允许登录用户读取和写入数据。 [码]
<tbody>
{clients.filter(client => client.userId === firebase.auth().currentUser.uid).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>
[/码]
我无法告诉任何人这种方法有多安全,但它确实有效。