Firebase handling multiple custom claims

Viewed 606

So i have a use case where a user may need multiple custom claims but added at seperate points of the app i.e a user can be both a shop keeper and a shop owner or they may just be a shop keeper or just a user.

I understand via the doc's that when you assign a new custom claim it writes over the original claims therefore i need to read what claims the user currently has. This is where i'm stuck...after i've recieved the claims how do I re-write them back to the user?

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{

    }

})

I suspect this is a pretty simple fix but i can't seem to find any examples anywhere of how to handle adding multiple claims at seperate times...stacking so to speak. Many thanks for your help in advance.

1 Answers

You're pretty close: you can use the spread operator (...) to add the existing claims and new claim into a single object:

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

Alternatively, you can simply extract the claims object from the user record and add your new claim to it before passing it back to setCustomUserClaims:

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

To delete a claim, you'd replace claims.gameAdmin = true; with delete claims.gameAdmin; in that previous snippet.

Related