我正在使用 firestore 和 firebase auth,我正在尝试将自定义用户名添加到我的应用程序(我正在学习本类(class),Next.js Firebase Full Course)连接到 freebase 模拟器,因为它仍在开发中。我有这段代码在 useEffect 中运行,它获取当前用户 uid,然后从 firestore 获取文档,然后检查它是否退出以及我是否确实将用户名状态设置为 do.xml 中的用户名。代码如下:
useEffect(() => {
let unsubscribe;
if (user) {
console.log(user.uid);
const ref = doc(db, "users", user.uid);
unsubscribe = onSnapshot(ref, (doc) => {
if (doc.exists()) {
setUsername(doc.data()?.username);
} else {
console.log("No such document!");
}
});
} else {
setUsername(null);
}
return unsubscribe;
}, [user]);
但我总是收到错误“next-dev.js?3515:32 快照监听器中 Uncaught Error :FirebaseError: false for 'get' @ L5”。我曾尝试将 on snapshot 更改为 get doc,但也会出现相同的错误。我试着让它没有连接到修复它的模拟器。我不知道为什么,但我喜欢使用 firebase 模拟器。有没有办法解决这个问题
提前致谢!
最佳答案
错误消息“FirebaseError : false for ‘get’@L5”表示安全规则在您的安全规则的第 5 行拒绝请求。如果您已经整理了如下规则,
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
}
}
然后第 5 行出现错误,因为您不允许任何人进行读写访问。 要解决此问题,您可以将 Firestore 规则更改为:
match /{document=**} { allow read: if true; allow write: if true; }
但这允许将您的规则设置为 true 以进行读取和写入操作,这意味着您允许任何知道您的项目 ID 的人读取和写入您的数据库,这显然是不好的,因为恶意用户可以利用它。确实,您可以将这些设置用于测试目的一小段时间,但绝不会在生产环境中使用。
因此,还有另一种选择,您可以将访问您的数据库的时间限制在固定的时间内。今天是 1.03.2021,我们将通过以下方式限制访问权限:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.time < timestamp.date(2021, 3, 2);
}
}
}
安全规则中最重要的部分是 Firebase Authentication ,这意味着您只能允许经过身份验证以在您的数据库中执行操作的用户进行访问。规则应如下所示:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if request.auth != null;
}
}
}
如果您需要一组更精细的规则,例如,只允许经过身份验证的用户(其 UID 的值等于来自身份验证过程的 UID 的值)能够写入他们的自己的文档,那么你应该考虑使用以下规则:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /users/{uid} {
allow create: if request.auth != null;
allow read, update, delete: if request.auth != null && request.auth.uid == uid;
}
}
}
一个 feature request被归档以使此错误消息更精确,例如 “FirebaseError: PERMISSION_DENIED because security rules returned false for 'get' @ L5”
关于google-cloud-firestore - "FirebaseError: false for ' 在快照上使用时得到 ' @ L5"firebase 错误,或者在使用 firebase 模拟器时得到 doc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71292824/