【问题标题】:Firebase handling multiple custom claimsFirebase 处理多个自定义声明
【发布时间】:2020-09-18 02:47:21
【问题描述】:

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

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

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{

    }

})

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

【问题讨论】:

    标签: javascript firebase firebase-authentication google-cloud-functions firebase-admin


    【解决方案1】:

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

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

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

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

    要删除声明,您可以在之前的 sn-p 中将 claims.gameAdmin = true; 替换为 delete claims.gameAdmin;

    【讨论】:

    • 弗兰克只是一个快速的,因为无论如何我可能最终会为此写另一个问题......然后我将如何着手删除该特定的自定义声明?
    • 在最后一个 sn-p 中,您将 claims.gameAdmin = true; 替换为 delete claims.gameAdmin
    • 谢谢,我知道 userRecord.customClaims 未定义...有什么想法吗?
    • 没关系,我必须添加 babel:npm install --save-dev babel-plugin-transform-object-rest-spread 然后我就可以使用您的代码上传到 firebase
    猜你喜欢
    • 2021-12-31
    • 2021-01-24
    • 2019-07-02
    • 2019-03-14
    • 1970-01-01
    • 2020-01-14
    • 2020-12-05
    • 1970-01-01
    • 2020-01-20
    相关资源
    最近更新 更多