Firebase 处理多个自定义声明

Jam*_*rey 1 javascript firebase firebase-authentication google-cloud-functions firebase-admin

所以我有一个用例,用户可能需要多个自定义声明,但在应用程序的不同点添加,即用户可以既是店主又是店主,或者他们可能只是店主或只是用户。

我通过文档了解到,当您分配新的自定义声明时,它会覆盖原始声明,因此我需要阅读用户当前拥有的声明。这就是我被卡住的地方......在我收到索赔后,我如何将它们重新写回给用户?

exports.onGameManagement = functions.database.ref("Core/CoreGames/{game}/teams/committee").onCreate((snapshot,context)=>{
    const position = snapshot.key;
    const uid = snapshot.val();
    const game = context.params.game;
    if(position=="gLead"||position=="depGameLead"){
        //NEEDS ADMIN RIGHTS
        //ADD TOKEN WRITE RIGHTS. - check for current claims
        admin.auth().getUser(uid).then((userRecord)=>{
            //got the users claims
            console.log(userRecord.customClaims);
            //how do i add this array of claims to the setCustomUserClaims() method?
            admin.auth().setCustomUserClaims(uid, {gameAdmin: true, userRecord.customClaims}).then(() => {
                // The new custom claims will propagate to the user's ID token the
                // next time a new one is issued.
              });
        })

    }else{

    }

})
Run Code Online (Sandbox Code Playgroud)

我怀疑这是一个非常简单的修复,但我似乎无法在任何地方找到任何关于如何处理在不同时间添加多个声明的示例......可以这么说。非常感谢您的帮助。

Fra*_*len 5

您非常接近:您可以使用扩展运算符 ( ...) 将现有声明和新声明添加到单个对象中:

admin.auth().getUser(uid).then((userRecord)=>{
    admin.auth().setCustomUserClaims(uid, {gameAdmin: true, ...userRecord.customClaims});
})
Run Code Online (Sandbox Code Playgroud)

或者,您可以简单地从用户记录中提取声明对象并将新声明添加到其中,然后再将其传回setCustomUserClaims

admin.auth().getUser(uid).then((userRecord)=>{
    let claims = userRecord.customClaims;
    claims.gameAdmin = true;
    admin.auth().setCustomUserClaims(uid, claims);
})
Run Code Online (Sandbox Code Playgroud)

要删除声明,您claims.gameAdmin = true;需要delete claims.gameAdmin;在之前的代码片段中替换为。