当用户注册时,应在Firestore中设置一个文档(database/users/${uid})。但是,我不断收到“权限缺失或不足”的消息。错误。
这是最相关的安全规则
match /users/{documents=**} {
allow read, create, update: if request.auth != null && request.auth.uid == resource.id
}
我尝试实现的另一条规则是
match /users/{uid=**} {
allow read, create, update: if request.auth != null && request.auth.uid == uid
}
这是注册用户并设置文档的代码
createUserWithEmailAndPassword(auth, emailInput, passwordInput).then(
(UserCredential) => {
console.log(UserCredential);
uid = UserCredential.user.uid;
sendEmailVerification(auth.currentUser).then(() => {
toast.success(
"Account created and email verification sent! Please check your inbox/spam folder",
{
duration: 10000,
}
);
setDoc(doc(db, "users", uid), {
userSettings: ["example", 0],
});
router.push("/verify");
});
}
);
为什么我无法将文档设置为访问我自己的用户文档的授权用户?
最佳答案
问题是request.auth.uid == resource.id
。来自 documentation ,
The
resource
variable refers to the requested document, and resource.data is a map of all of the fields and values stored in the document.
但是该文档不存在,因为用户刚刚注册到您的应用程序。
尝试以下规则:
match /users/{userId} {
allow read, create, update: if request.auth != null && request.auth.uid == userId;
}
此规则将确保用户只能使用其用户 ID 创建/读取/更新文档。
另请注意,匹配路径为 /users/{userId}
,与您的问题中的 /users/{userId=**}
不匹配。如果您使用 recursive wilcard (=**
),userId
的值将是 /userID
而不仅仅是 userID
。并且规则总是会失败。
如果必须将规则应用于所有嵌套集合,则在下一个路径段上使用递归通配符:
match /users/{userId}/{path=**} {
// ... can still read userId
}
关于firebase - 如何为用户设置不存在的文档编写安全规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73958252/