6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Custom User Claimを追記する

Last updated at Posted at 2019-12-28

Custom Claimを利用する方法は以前にも書いたのですが、標準関数であるsetCustomUserClaim()は標準では上書きされてしまうようです。

どういうことかというと、

{A:true,B:true}

という結果を得るために、

setCustomUserClaim(uid,{A:true});
setCustomUserClaim(uid,{B:true});

とすると、

{B:true}

となります。
これを{A:true,B:true}としたいのです。

 基本動作の確認

CustomUserClaimsはadminじゃないと操作できませんのでfirebase-adminを利用します。
また予めユーザーを作成し、uidを取得した状態から操作しています。

まず通常のsetCustomUserClaims()の動作を確認。

const admin = require('firebase-admin');
admin.initializeApp({
    credential: admin.credential.cert('/path/to/key.json'),
    databaseURL: 'https://xxxxx.firebaseio.com',
});

(async () => {

	//uid
	const uid = "cI4FbDfSMCMUMXVcn1TlZTpGKQn2";

    //Custom Claim通常設定
    await admin.auth().setCustomUserClaims(uid, {});
    await admin.auth().setCustomUserClaims(uid, { A: true });
    await admin.auth().setCustomUserClaims(uid, { B: true });

    //Custom Claim表示
    const user = await admin.auth().getUser(uid);
    console.log(user.customClaims);

})();

実行結果。上書きされています。

{ B: true }

追記(その1)

では追記。カスタム関数を作成するパータン。

const admin = require('firebase-admin');
admin.initializeApp({
    credential: admin.credential.cert('/path/to/key.json'),
    databaseURL: 'https://xxxxx.firebaseio.com',
});

//追記のための関数
const addCustomUserClaims = async (uid, claims) => {

    const user = await admin.auth().getUser(uid);
    let updateClaims = user.customClaims || {};

    for (let property in claims) {
        if (Object.prototype.hasOwnProperty.call(claims, property)) {
            updateClaims[property] = claims[property];
        }
    }

    await admin.auth().setCustomUserClaims(uid, updateClaims);

}

(async () => {

    const uid = "cI4FbDfSMCMUMXVcn1TlZTpGKQn2";

    //Custom Claimの追記
    await addCustomUserClaims(uid, { A: true });
    await addCustomUserClaims(uid, { B: true });

    //Custom Claim再表示
    const user = await admin.auth().getUser(uid);
    console.log(user.customClaims);

})();

実行。追記されてます。

{ B: true, A: true }

追記(その2)

オブジェクトをマージすればいいだけな気もします。

const user = await admin.auth().getUser(uid);
await admin.auth().setCustomUserClaims(user.uid,{...user.customClaims,...{A:true});
await admin.auth().setCustomUserClaims(user.uid,{...user.customClaims,...{B:true});

参考

6
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?