# 会員管理 データの移行

このセクションでは、Firebase Admin SDKを使用して、NCMB会員管理システムからFirebase Authenticationへのデータ移行方法をご紹介します。

特に、パスワードを使用している会員管理システムをお使いの方は、以下の重要な点に注意してください。

**2023年12月20日時点で、NCMB会員管理システムのパスワードハッシュアルゴリズムについての情報は公開されていません。このため、データをFirebaseに移行した後、ユーザーに対してパスワードの再設定をお願いする必要があります。**

具体的には、まずNCMBからFirebaseへ会員データを移行しますが、この時点ではパスワード情報は含まれません。また、ユーザーのメールアドレスが本人確認済みでない場合も考慮されます。このプロセスを通じて、Firebase Authenticationに安全にデータを移行する方法を解説します。

また、データ移行後のアプリケーションでユーザーがパスワードを再設定するための手順やサンプルコードについては、別のセクションで詳しく説明します。

本ドキュメントで扱うコードはGitHubリポジトリにて公開しています。

{% embed url="<https://github.com/monaca-samples/authentication-migration>" %}

## 移行ツールのディレクトリ構成

移行ツールのディレクトリ構成は次のようになります。

`user.json` 、`serviceAccountKey.json` の準備の仕方は次の項以降で説明します。

```markup
.
├── data
│   └── user.json           # NCMBからエクスポートした会員管理のuser.jsonを配置
├── importWithEmail.js      # 実行ファイル（メールアドレスを使った認証。本セクションで解説）
├── importWithUserName.js   # 実行ファイル（ユーザー名を使った認証。次セクションで解説）
├── node_modules
├── package-lock.json
├── package.json
└── serviceAccountKey.json  # Firebaseからエクスポートしたサービスアカウント秘密鍵を配置
```

## 1. 移行ツールの準備

1. GitHubリポジトリ[authentication-migration](https://github.com/monaca-samples/authentication-migration)をローカル環境にcloneします。

```bash
git clone https://github.com/monaca-samples/authentication-migration.git
```

2. `authentication-migration` ディレクトリに移動し、下記を実行します。

```bash
npm install
```

## 2. Firebaseサービスアカウント秘密鍵の生成

* Firebase Consoleを開き、移行先プロジェクトの「プロジェクトの設定」ページにアクセスします。
* 「サービスアカウント」タブをクリックし、Firebase Admin SDKセクションの「新しい秘密鍵を生成」ボタンをクリックします。

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/ae6d7c55-1dfe-484b-af16-1c3c37cb281f.png" alt="" width="375"><figcaption></figcaption></figure>

jsonファイルがダウンロードされるので、`authentication-migration`リポジトリ直下に `serviceAccountKey.json` という名前でコピーします。

## 3. Firebase Authenticationの有効化

Firebaseコンソールにアクセスし、`Firebase Authentication` を有効化します。

1. 左メニューの「全てのプロダクト」をクリック、表示された「Authentication」をクリックします。

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/aee9e9db-9a2a-4da2-8702-985949b74d7e.png" alt="" width="375"><figcaption></figcaption></figure>

2. 「始める」をクリックします。

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/d156733b-0d5a-4037-bd3b-2fbaa81d730d.png" alt="" width="375"><figcaption></figcaption></figure>

3. 「Sign-in method」タブのログインプロバイダでは、「メール/パスワード」を選択します。

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/11278ea3-bca4-448e-88ac-c16f8290cf04.png" alt="" width="375"><figcaption></figcaption></figure>

4. 「メール/パスワード」の「有効にする」スイッチをオンにし、「保存」ボタンをクリックします。

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/e72e4bbf-1179-4dfd-9973-7b3744a4f0c1.png" alt="" width="375"><figcaption></figcaption></figure>

## 4. NCMB会員管理のエクスポート

ニフクラ Mobile Backendからのデータのエクスポートは、次の手順で行います。

1. ニフクラ Mobile Backendでプロジェクトにアクセスし、右上のアプリ設定をクリック

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/2ef21e65-e810-4efe-b7f1-d60b4c409556.png" alt="" width="375"><figcaption></figcaption></figure>

2. メニューから「エクスポート」を選択し、エクスポートボタンをクリック

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/af5e1373-248b-4651-a62b-0cc6a67bb7e9.png" alt="" width="375"><figcaption></figcaption></figure>

3. エクスポートダイアログでエクスポートを実行すると、登録されているメールアドレスにデータをダウンロードするURLが届きます

<figure><img src="https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/c594916c-1072-4d59-983f-aaa41319e850.png" alt="" width="375"><figcaption></figcaption></figure>

ダウンロードしたデータは、JSON形式でクラス毎に別々のファイルとして出力されます。会員管理のデータ移行では `user.json` を利用します。下の内容は、エクスポートされたJSONファイルの中身の例です。

```json
{
  "results": [
    {
      "userName": "SampleUser",
      "password": "hashed_password_example",
      "temporaryPassword": null,
      "authData": null,
      "mailAddressConfirm": false,
      "mailAddress": "example@example.com",
      "acl": {
        "exampleObjectId": {
          "read": true,
          "write": true
        }
      },
      "createDate": {
        "__type": "Date",
        "iso": "2023-01-01T00:00:00.000Z"
      },
      "updateDate": {
        "__type": "Date",
        "iso": "2023-01-02T00:00:00.000Z"
      },
      "phone_number": "000-0000-0000",
      "objectId": "exampleObjectId"
    }
  ]
}
```

4. ダウンロードした `user.js` を `authentication-migration/data`ディレクトリにコピーします。

## 5. Firebase Authenticationへのインポート

インポートは、次のコマンドで実行します。ダウンロードしたサービスアカウントの秘密鍵の情報に基づき、クラウド上のプロジェクトにデータをインポートします。エミュレーターを利用する方法については後述します。

```bash
npm run import
```

移行したデータを確認します。Firebase Consoleにアクセスし、左メニュー「Authentication」をクリックします。 さらに「Users」タブをクリックすると、移行したデータが表示されます。

![image.png (62.1 kB)](https://img.esa.io/uploads/production/attachments/19330/2023/12/20/125451/42968b0b-c155-4351-800d-2ddab84d8997.png)

### 実行ファイル (importWithEmail.js) の解説

importWithEmail.js 内の下記の部分 ( <https://github.com/monaca-samples/authentication-migration/blob/311bdaa8b5e75a2ce10fa9a748920e4272495d64/importWithEmail.js#L18-L25> ) にて、NCMB会員管理データとFirbase Authenticationのデータをマッピングしています。

```javascript
.importUsers([
    {
        uid: user.objectId,         // NCMBのユーザーIDをFirebaseのUIDにマッピングします。
        displayName: user.userName, // NCMBのユーザー名をFirebaseの表示名（displayName）にマッピングします。
        email: user.mailAddress,    // NCMBのメールアドレスをFirebaseのメールアドレスにマッピングします。
        emailVerified: false,       // メールアドレスの確認状態。ここでは、初期状態を未確認（false）としています。
    },
])
```

Authenticationへのインポートについての詳細は、下のドキュメントを参照してください。\
このサンプルではNCMB側にmailAddressが存在する前提のコードになっています。NCMB側に保存されているデータの状況に応じて、登録するフィールドを調整してください。 メールアドレスを認証に使用していない場合は、電話番号やSNS認証の移行を検討してください。

{% embed url="<https://firebase.google.com/docs/auth/admin/import-users?hl=ja>" %}

## エミュレーターを利用する

Firebaseのクラウド環境に接続して移行を行う前に、ローカル環境でFirebaseのエミュレーターを稼働させてデータの移行を検証できます。

1. Firebaseのエミュレーターを起動する。詳細はこちらを参照してください。&#x20;

{% content-ref url="/pages/MoILIEcFnFr5fD3XnBRE" %}
[Firebase Authentication パスワード再設定サンプル](/migration-guide/nifcloud/authentication/firebase-authentication-pasuwdosanpuru.md)
{% endcontent-ref %}

2. 下記のコマンドで移行を実行する

```bash
npm run import:emu
```

### まとめ

本項ではNCMB会員管理のデータをFirebase Authenticationに移行する方法を解説しました。この状態ではユーザーはログインできないため、パスワードの再設定を行う必要があります。次項でパスワード再設定を行うサンプルを解説します。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://ja.docs.monaca.io/migration-guide/nifcloud/authentication/migration.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
