首页 > 解决方案 > 无法获取要显示的客户端数据 [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>

[/代码]

我不确定我做错了什么,是安全规则还是我选择如何显示数据?

标签: reactjsfirebase-authenticationfirebase-security

解决方案


我的理解是你有一个客户集合和一个用户集合。用户可以创建客户端,并且只能查看/编辑/删除他们创建的客户端,对吗?如果是这样,只需添加一个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


推荐阅读