如何为设置文档的用户编写安全规则;不存在



当用户注册时,应在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。从文件来看,

resource变量指的是请求的文档,resource.data是文档中存储的所有字段和值的映射。

但是文档不存在,因为用户刚刚注册到您的应用程序。

请尝试以下规则:

match /users/{userId} {
allow read, create, update: if request.auth != null && request.auth.uid == userId;
}

此规则将确保用户只能使用其用户ID创建/读取/更新文档。

还要注意,匹配路径是/users/{userId},而不是像您的问题中那样与/users/{userId=**}匹配。如果使用递归wilcard(=**(,则userId的值将是/userID,而不仅仅是userID,并且规则将始终失败。


如果该规则必须应用于所有嵌套集合,则在下一个路径段上使用递归通配符:

match /users/{userId}/{path=**} {
// ... can still read userId
}

最新更新