云函数,删除Firestore子集合,是否需要AdminToken



我正在尝试构建可调用的云函数,当用户删除帖子时,它也会尝试删除评论,这是帖子的子集合。所以我看到了这个示例,并像文档示例一样实现

const admin = require('firebase-admin');
const firebase_tools = require('firebase-tools');
const functions = require('firebase-functions');
admin.initializeApp({
serviceAccountId: 'xxxxxx-xxxxx@appspot.gserviceaccount.com'
}
);
exports.mintAdminToken = functions.https.onCall(async (data: any, context: any) => {
const uid = data.uid;
const token = await admin
.auth()
.createCustomToken(uid, { admin: true });
return { token };
});
exports.recursiveDelete = functions
.runWith({
timeoutSeconds: 540,
memory: '2GB'
})
.https.onCall(async (data: any, context: any) => {
// Only allow admin users to execute this function.
if (!(context.auth && context.auth.token && context.auth.token.admin)) {
throw new functions.https.HttpsError(
'permission-denied',
'Must be an administrative user to initiate delete.'
);
}
const path = data.path;
console.log(
`User ${context.auth.uid} has requested to delete path ${path}`
);
await firebase_tools.firestore
.delete(path, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
yes: true,
token: functions.config().fb.token
});
return {
path: path 
};
});

并且我成功地将自定义令牌接收到客户端。但我现在该怎么办?在得到代币后,我称之为";recursiveDelete";函数,但发生错误PERMISSION_DENIED

  1. 是否应该使用新的自定义管理令牌初始化接收令牌的用户?(如果我误解了,请告诉我(
  2. 删除这样的子集合时,管理员令牌真的有必要吗?它很难使用,所以我问

我不认为您真的需要这个用例的自定义令牌,我建议您使用firebase firestore规则,而不是实现自己的基于角色的身份验证。

要遵循的步骤:

1-创建一个集合,您可以称之为";用户";并且在其中包括该用户可能具有的角色的字段,例如";ADMIN";。该集合中的每个文档id都可以是firebaseauth生成的用户的authuid。您可以使用currentUser道具从前端获取这个uid,这里已经解释了

2-使用firestore规则保护您的数据库,例如:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// only admins can remove posts
match /posts/{postID} {
allow read, write: if isAdmin();
}
// only admins can remove comments
match /comments/{commentID} {
allow read, write: if isAdmin();
}
// this function will check if the caller has an admin role and allow or disallow the task upon that
function isAdmin() {
return get(/databases/$(database)/documents/
users/$(request.auth.uid)).data.role == "ADMIN";
}
}
}

3-在你成功删除一个帖子文档后,你可以用onDelete触发器创建一个函数,该函数被调用并删除注释子集合递归,要做到这一点,你应该包括以下代码:

const client = require('firebase-tools');
exports.recursiveDelete = functions.firestore
.document('posts/{postID}')
.onDelete((snap, context) => {
.....
await client.firestore
.delete(collectionPath, {
project: process.env.GCLOUD_PROJECT,
recursive: true,
yes: true
});
} 

相关内容

  • 没有找到相关文章

最新更新