> ## Documentation Index
> Fetch the complete documentation index at: https://translations.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Verify データベースアクションスクリプトとテンプレート

> Verify スクリプトは、ユーザーが Auth0 の確認メール内のリンクをたどったときに実行されます。

Verify スクリプトは、外部データベース内でユーザーのメールアドレスのステータスを更新するために実行される関数を実装します。この関数名は `verify` にすることを推奨します。

このスクリプトはレガシー認証のシナリオでのみ使用され、ユーザーのメールアドレス確認をサポートするために必要です。確認済みメールアドレスは Auth0 のさまざまなワークフローシナリオで重要であり、このスクリプトを実装することで、これらを標準でサポートできるようになります。

有効になっている場合、このスクリプトは、ユーザーが Auth0 から送信された確認メール内のリンクをクリックしたときに実行されます。

<div id="verify-function">
  ## Verify 関数
</div>

`verify` 関数は、次の処理を行う必要があります。

* 外部データベース内のユーザーのプロファイルにある `email_verified` (または同等の) 属性を更新する。
* 更新処理が成功した場合は `true` を返す。
* 更新処理が失敗した場合はエラーを返す。

<div id="definition">
  ### 定義
</div>

`verify`関数は2つのパラメータを受け取り、コールバック関数を返します。

```js theme={null}
verify(email, callback): function
```

| パラメータ      | 型        | 説明                                   |
| ---------- | -------- | ------------------------------------ |
| `email`    | String   | ユーザーのメールアドレス。                        |
| `callback` | Function | エラーまたはプロファイルデータをパイプライン経由で渡すために使用します。 |

これは、`login`関数の実装方法を示す疑似JavaScriptの例です：

```javascript lines theme={null}
function verify(email, callback) {
  // 外部データベースAPIにメールを送信する
  let options = {
    url: "https://example.com/api/verify",
    body: {
      email: email
    }
  };

  send(options, (err) => {
    // 更新に失敗した場合はコールバックでエラーを返す
    if (err) {
      return callback(new Error(email, "My custom error message."));
    } else {
      // 更新に成功した場合はコールバックでtrueを返す
      return callback(null, true);
    }
  });
}
```

<div id="callback-function">
  ## コールバック関数
</div>

`callback`関数は、ユーザープロファイルデータやエラーデータをパイプライン内で受け渡すために使用されます。

<div id="definition">
  ### 定義
</div>

コールバック関数は、最大 2 つのパラメータを受け取り、関数を返します。

```js theme={null}
callback(error, [verified]): function
```

| パラメータ      | 型       | 必須 | 説明                                                                        |
| ---------- | ------- | -- | ------------------------------------------------------------------------- |
| `error`    | オブジェクト  | 必須 | エラーデータが含まれます。                                                             |
| `verified` | Boolean | 任意 | 外部データベースにおけるユーザーのステータスを表す値 (`true` または `false`) が含まれます。`true` の場合にのみ必要です。 |

<div id="return-a-success">
  ### 成功を返す
</div>

外部データベースでユーザーのステータスが正常に更新された場合は、`error` パラメータに `null` を、`verified` パラメータに `true` を渡します。

```js theme={null}
callback(null, true);
```

<Callout icon="file-lines" color="#0EA5E9" iconType="regular">
  Verify スクリプトは、`callback` 関数でどのような値が返されても、ユーザーの Auth0 プロファイル内の `email_verified` 属性の値を変更しません。

  ユーザーの Auth0 プロファイル内の `email_verified` 属性を更新するには、[Login](/docs/ja-jp/authenticate/database-connections/custom-db/templates/login) スクリプトと [Get User](/docs/ja-jp/authenticate/database-connections/custom-db/templates/get-user) スクリプトで返されるユーザープロファイルオブジェクトに、`email_verified` 属性とその値を含める必要があります。
</Callout>

<div id="return-an-error">
  ### エラーを返す
</div>

エラーが発生した場合、`error`パラメータには何が問題だったのかを示す関連情報を含める必要があります：

```js theme={null}
return callback(new Error("My custom error message."));
```

<div id="language-specific-script-examples">
  ## 言語別のスクリプト例
</div>

Auth0 は、以下の言語／テクノロジー向けのサンプルスクリプトを提供しています。

<CodeGroup>
  ```javascript JavaScript lines theme={null}
  function verify(email, callback) {
    // このスクリプトは、現在のユーザーのメールアドレスを
    // データベース内で確認済みとしてマークするべきです。
    // ユーザーがメールで送信された確認リンクをクリックするたびに実行されます。
    // これらのメールは https://manage.auth0.com/#/emails でカスタマイズできます。
    // 確認メールは有効になっている場合、サインアップ成功直後に送信されるため、
    // ユーザーのメールアドレスがすでにデータベースに存在すると仮定して問題ありません。
    //
    // このスクリプトは次の2通りの方法で終了します:
    // 1. ユーザーのメールアドレスが正常に確認された場合
    //     callback(null, true);
    // 2. データベースにアクセスする際に何か問題が発生した場合:
    //     callback(new Error("my error message"));
    //
    // エラーが返されると、確認リンクをクリックした後にユーザーがリダイレクトされるページの
    // クエリ文字列にそのエラーが渡されます。
    // 例えば、`callback(new Error("error"))` を返して
    // https://example.com にリダイレクトすると、次の URL にリダイレクトされます:
    //     https://example.com?email=alice%40example.com&message=error&success=false
    const msg = 'Please implement the Verify script for this database connection ' +
      'at https://manage.auth0.com/#/connections/database';
    return callback(new Error(msg));
  }
  ```

  ```javascript ASP.NET MVC3 lines expandable theme={null}
  // ASP.NET Membership Provider（MVC3 - Universal Providers）用
  function verify(email, callback) {
    const sqlserver = require('tedious@1.11.0');
    const Connection = sqlserver.Connection;
    const Request = sqlserver.Request;
    const TYPES = sqlserver.TYPES;
    const connection = new Connection({
      userName: 'the username',
      password: 'the password',
      server: 'the server',
      options: {
        database: 'the db name',
        encrypt: true,
        // Required to retrieve userId needed for Membership entity creation
        rowCollectionOnRequestCompletion: true
      }
    });
    connection.on('debug', function(text) {
      // if you have connection issues, uncomment this to get more detailed info
      //console.log(text);
    }).on('errorMessage', function(text) {
      // SQLデータベースへの接続時またはSQLステートメントに関するエラーを表示します
      console.log(JSON.stringify(text));
    });
    connection.on('connect', function(err) {
      if (err) return callback(err);
      verifyMembershipUser(email, function(err, wasUpdated) {
        if (err) return callback(err); // this will return a 500
        callback(null, wasUpdated);
      });
    });
    function verifyMembershipUser(email, callback) {
      // isApprovedフィールドはメールアドレス確認フラグです
      const updateMembership =
        'UPDATE Memberships SET isApproved = \'true\' ' +
        'WHERE isApproved = \'false\' AND Email = @Email';
      const updateMembershipQuery = new Request(updateMembership, function(err, rowCount) {
        if (err) {
          return callback(err);
        }
        callback(null, rowCount > 0);
      });
      updateMembershipQuery.addParameter('Email', TYPES.VarChar, email);
      connection.execSql(updateMembershipQuery);
    }
  }
  ```

  ```javascript ASP.NET MVC4 lines expandable theme={null}
  // ASP.NET Membership Provider（MVC4 - Simple Membership）用
  function verify (email, callback) {
    const sqlserver = require('tedious@1.11.0');
    const Connection = sqlserver.Connection;
    const Request = sqlserver.Request;
    const TYPES = sqlserver.TYPES;
    const connection = new Connection({
      userName: 'the username',
      password: 'the password',
      server: 'the server',
      options: {
        database: 'the db name',
        encrypt: true,
        // Required to retrieve userId needed for Membership entity creation
        rowCollectionOnRequestCompletion: true
      }
    });
    connection.on('debug', function(text) {
      // if you have connection issues, uncomment this to get more detailed info
      //console.log(text);
    }).on('errorMessage', function(text) {
      // SQLデータベースへの接続時またはSQLステートメントに関するエラーを表示します
      console.log(JSON.stringify(text));
    });
    connection.on('connect', function (err) {
      if (err) return callback(err);
      verifyMembershipUser(email, function(err, wasUpdated) {
        if (err) return callback(err); // this will return a 500
        callback(null, wasUpdated);
      });
    });
    function findUserId(email, callback) {
      const findUserIdFromEmail =
        'SELECT UserProfile.UserId FROM ' +
        'UserProfile INNER JOIN webpages_Membership ' +
        'ON UserProfile.UserId = webpages_Membership.UserId ' +
        'WHERE UserName = @Username';
      const findUserIdFromEmailQuery = new Request(findUserIdFromEmail, function (err, rowCount, rows) {
        if (err || rowCount < 1) return callback(err);
        const userId = rows[0][0].value;
        callback(null, userId);
      });
      findUserIdFromEmailQuery.addParameter('Username', TYPES.VarChar, email);
      connection.execSql(findUserIdFromEmailQuery);
    }
    function verifyMembershipUser(email, callback) {
      findUserId(email, function (err, userId) {
        if (err || !userId) return callback(err);
        // isConfirmed field is the email verification flag
        const updateMembership =
          'UPDATE webpages_Membership SET isConfirmed = \'true\' ' +
          'WHERE isConfirmed = \'false\' AND UserId = @UserId';
        const updateMembershipQuery = new Request(updateMembership, function (err, rowCount) {
          return callback(err, rowCount > 0);
        });
        updateMembershipQuery.addParameter('UserId', TYPES.VarChar, userId);
        connection.execSql(updateMembershipQuery);
      });
    }
  }
  ```

  ```javascript MongoDB lines theme={null}
  function verify (email, callback) {
    const MongoClient = require('mongodb@3.1.4').MongoClient;
    const client = new MongoClient('mongodb://user:pass@mymongoserver.com');
    client.connect(function (err) {
      if (err) return callback(err);
      const db = client.db('db-name');
      const users = db.collection('users');
      const query = { email: email, email_verified: false };
      users.update(query, { $set: { email_verified: true } }, function (err, count) {
        client.close();
        if (err) return callback(err);
        callback(null, count > 0);
      });
    });
  }
  ```

  ```javascript MySQL lines theme={null}
  function verify(email, callback) {
    const mysql = require('mysql');
    const connection = mysql({
      host: 'localhost',
      user: 'me',
      password: 'secret',
      database: 'mydb'
    });
    connection.connect();
    const query = 'UPDATE users SET email_Verified = true WHERE email_Verified = false AND email = ?';
    connection.query(query, [ email ], function(err, results) {
      if (err) return callback(err);
      callback(null, results.length > 0);
    });
  }
  ```

  ```javascript PostgreSQL lines theme={null}
  function verify (email, callback) {
    //この例では「pg」ライブラリを使用します
    //詳細: https://github.com/brianc/node-postgres
    const postgres = require('pg');
    const conString = 'postgres://user:pass@localhost/mydb';
    postgres.connect(conString, function (err, client, done) {
      if (err) return callback(err);
      const query = 'UPDATE users SET email_Verified = true WHERE email_Verified = false AND email = $1';
      client.query(query, [email], function (err, result) {
        // 注: データベース接続を閉じるため、ここでは必ず`done()`を呼び出します
        done();
        return callback(err, result && result.rowCount > 0);
      });
    });
  }
  ```

  ```javascript SQL Server lines expandable theme={null}
  function verify (email, callback) {
    //この例では「tedious」ライブラリを使用します
    //詳細はこちら: http://pekim.github.io/tedious/index.html
    const sqlserver = require('tedious@1.11.0');
    const Connection = sqlserver.Connection;
    const Request = sqlserver.Request;
    const TYPES = sqlserver.TYPES;
    const connection = new Connection({
      userName:  'test',
      password:  'test',
      server:    'localhost',
      options:  {
        database: 'mydb'
      }
    });
    const query = 'UPDATE dbo.Users SET Email_Verified = true WHERE Email_Verified = false AND Email = @Email';
    connection.on('debug', function(text) {
      console.log(text);
    }).on('errorMessage', function(text) {
      console.log(JSON.stringify(text, null, 2));
    }).on('infoMessage', function(text) {
      console.log(JSON.stringify(text, null, 2));
    });
    connection.on('connect', function (err) {
      if (err) return callback(err);
      const request = new Request(query, function (err, rows) {
        if (err) return callback(err);
        callback(null, rows > 0);
      });
      request.addParameter('Email', TYPES.VarChar, email);
      connection.execSql(request);
    });
  }
  ```

  ```javascript Azure SQL Database lines expandable theme={null}
  function verify (email, callback) {
    //この例では「tedious」ライブラリを使用します
    //詳細はこちら: http://pekim.github.io/tedious/index.html
    var Connection = require('tedious@1.11.0').Connection;
    var Request = require('tedious@1.11.0').Request;
    var TYPES = require('tedious@1.11.0').TYPES;
    var connection = new Connection({
      userName:  'your-user@your-server-id.database.windows.net',
      password:  'the-password',
      server:    'your-server-id.database.windows.net',
      options:  {
        database: 'mydb',
        encrypt:  true
      }
    });
    var query =
      'UPDATE Users SET Email_Verified=\'TRUE\' ' +
      'WHERE Email_Verified=\'FALSE\' AND Email=@Email';
    connection.on('debug', function(text) {
      // デバッグメッセージを有効にするには、次の行のコメントを解除します
      // console.log(text);
    }).on('errorMessage', function(text) {
      console.log(JSON.stringify(text, null, 2));
    }).on('infoMessage', function(text) {
      // 情報メッセージを有効にするには、次の行のコメントを解除します
      // console.log(JSON.stringify(text, null, 2));
    });
    connection.on('connect', function (err) {
      if (err) { return callback(err); }
      var request = new Request(query, function (err, rows) {
        if (err) { return callback(err); }
        console.log('rows: ' + rows);
        callback(null, rows > 0);
      });
      request.addParameter('Email', TYPES.VarChar, email);
      connection.execSql(request);
    });
  }
  ```
</CodeGroup>
