所以我已经构建了一个前端,现在我正在开发一个具有基于自定义声明的安全规则的后端。我收到一个我无法理解的错误。我已经运行了可调用函数并注销并重新登录,但当我尝试更改文档详细信息时仍然收到错误消息。我正在尝试编辑 firestore 中的文档,该文档属于用户。因此,要么用户进行更改,要么管理员可以进行更改。
编辑提交:
const onSubmit = async () => {
const editRef = doc(db, `images/${imageID}`);
try {
await updateDoc(editRef, {
aLabels: aLabels,
});
} catch (error) {
console.log(error.message);
toast.error("Something went wrong");
}
}
adminClaims.js
const functions = require("firebase-functions");
const admin = require("firebase-admin");
exports.setAdminClaims = functions.https.onRequest(async (req, res) => {
const adminUIDs = [
"pyqPlr3BT7LwzxBerxi1seqDrv6x"
];
await Promise.all(
adminUIDs.map((uid) =>
admin.auth().setCustomUserClaims(uid, { admin: true })
)
);
res.send("Done configuring rules");
});
firestore 安全规则
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false; //line 5
}
match /images/{image} {
allow read: if true;
allow create: if isLoggedIn() //line 16
allow update, delete: if isLoggedIn() && isOwner() || isAdmin()
}
function isLoggedIn() {
return request.auth.uid != null;
}
function isOwner() {
return request.auth.uid == resource.data.user
}
function isAdmin() {
return request.auth.token.role.admin == true
}
}
错误信息
PERMISSION_DENIED:“更新”@L5 为 false,评估错误位于 L16:32 表示“更新”@ L16,“更新”@L5 为 false,属性角色为 对象上未定义。 “更新”@L16
错误非常明显:您的令牌没有
role
属性,因此您的 isAdmin
函数失败:
function isAdmin() {
return request.auth.token.role.admin == true
}
根据您设置自定义声明的方式,规则中的功能应该是:
function isAdmin() {
return request.auth.token.admin == true
}