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

# 検証スクリプトのテンプレート

> ユーザーのメール検証を行うための、カスタムデータベースのアクションスクリプト用テンプレートについて説明します。

検証スクリプトは、ユーザーのメールアドレスが外部データベースにある場合に、検証ステータスを検証済みにする関数を実装します。この関数の名前は`verify`にすることをお勧めします。

このスクリプトはレガシーの認証シナリオでのみ使用され、ユーザーのメールアドレス検証に対応する必要があります。メールアドレスが検証済みであることは、Auth0にあるいくつかのワークフローのシナリオでは不可欠であるため、このスクリプトを実装しておけば、そのままでそれらのシナリオに対応できます。

有効化されると、ユーザーがAuth0から受け取った確認メールのリンクをクリックしたときに、このスクリプトが実行されます。

## 検証関数

`verify`関数は以下を行います。

* 外部データベースにあるユーザープロファイルの`email_verified`（またはそれと同等の）属性を更新します。
* 更新のアクションが成功した場合には、`true`を返します。
* 更新のアクションが失敗した場合には、エラーを返します。

### 定義

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

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

| パラメーター     | 種類  | 説明                                  |
| ---------- | --- | ----------------------------------- |
| `email`    | 文字列 | ユーザーのメールアドレス。                       |
| `callback` | 関数  | パイプラインを通してエラーやプロファイルデータを渡すのに使用すされる。 |

### 例

これは疑似JavaScriptを使った例で、どのようにすれば`login`関数を実装できるかがわかります。言語固有の例については、「[言語固有のスクリプトの例](https://auth0.com/docs/authenticate/database-connections/custom-db/templates/verify#language-specific-script-examples)」をお読みください。

```javascript lines theme={null}
function verify(email, callback) {
  // Send email to external database API
  let options = {
    url: "https://example.com/api/verify",
    body: {
      email: email
    }
  };

  send(options, (err) => {
    // Return error in callback if update failed
    if (err) {
      return callback(new Error(email, "My custom error message."));
    } else {
      // Return true in callback if update succeeded
      return callback(null, true);
    }
  });
}
```

## コールバック関数

`callback`関数は、パイプラインを通してユーザープロファイルデータやエラーデータを渡すのに使用されます。

### 定義

`callback`関数は2つまでのパラメーターを受け取り、1つの関数を返します。

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

| パラメーター     | タイプ    | 必須 | 説明                                                            |
| ---------- | ------ | -- | ------------------------------------------------------------- |
| `error`    | オブジェクト | 必須 | エラーデータが含まれます。                                                 |
| `verified` | ブール値   | 任意 | 外部データベースにおけるユーザーの確認状態を示す値（`true`または`false`）。値が`true`の場合にのみ必須。 |

### 成功の場合

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

<Warning>
  `callback`関数で返される値にかからわず、検証スクリプトによってユーザーのAuth0プロファイルにある`email_verified`属性の値が変更されることはありません。

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

#### 例

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

### エラーの場合

エラーが発生した場合には、何が起きたかについての関連情報が`error`パラメーターに含まれるようにします。

#### 例

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

## 言語固有のスクリプトの例

Auth0は、以下の言語や技術で使用できるサンプルスクリプトを提供しています。

* [JavaScript](#javascript)
* [ASP.NET Membership Provider（MVC3 - Universal Providers）](#asp-net-membership-provider-mvc3-universal-providers-)
* [ASP.NET Membership Provider（MVC4 - Universal Providers）](#asp-net-membership-provider-mvc4-simple-membership-)
* [MongoDB](#mongodb)
* [MySQL](#mysql)
* [PostgreSQL](#postgresql)
* [SQL Server](#sql-server)
* [Windows Azure SQL Database](#windows-azure-sql-database)

### JavaScript

```javascript lines theme={null}
function verify(email, callback) {
  // This script should mark the current user's email address as verified in
  // your database.
  // It is executed whenever a user clicks the verification link sent by email.
  // These emails can be customized at https://manage.auth0.com/#/emails.
  // It is safe to assume that the user's email already exists in your database,
  // because verification emails, if enabled, are sent immediately after a
  // successful signup.
  //
  // There are two ways that this script can finish:
  // 1. The user's email was verified successfully
  //     callback(null, true);
  // 2. Something went wrong while trying to reach your database:
  //     callback(new Error("my error message"));
  //
  // If an error is returned, it will be passed to the query string of the page
  // where the user is being redirected to after clicking the verification link.
  // For example, returning `callback(new Error("error"))` and redirecting to
  // https://example.com would redirect to the following 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));
}
```

### ASP.NET Membership Provider（MVC3 - Universal Providers）

```javascript lines expandable theme={null}
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) {
    // this will show any errors when connecting to the SQL database or with the SQL statements
    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 field is the email verification flag
    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);
  }
}
```

### ASP.NET Membership Provider（MVC4 - Universal Providers）

```javascript lines expandable theme={null}
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) {
    // this will show any errors when connecting to the SQL database or with the SQL statements
    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);
    });
  }
}
```

### MongoDB

```javascript 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);
    });
  });
}
```

### MySQL

```javascript 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);
  });
}
```

### PostgreSQL

```javascript lines theme={null}
function verify (email, callback) {
  //this example uses the "pg" library
  //more info here: 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) {
      // NOTE: always call `done()` here to close
      // the connection to the database
      done();
      return callback(err, result && result.rowCount > 0);
    });
  });
}
```

### SQL Server

```javascript lines expandable theme={null}
function verify (email, callback) {
  //this example uses the "tedious" library
  //more info here: 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);
  });
}
```

### Windows Azure SQL Database

```javascript lines expandable theme={null}
function verify (email, callback) {
  //this example uses the "tedious" library
  //more info here: 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) {
    // Uncomment next line in order to enable debugging messages
    // console.log(text);
  }).on('errorMessage', function(text) {
    console.log(JSON.stringify(text, null, 2));
  }).on('infoMessage', function(text) {
    // Uncomment next line in order to enable information messages
    // 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);
  });
}
```

## もっと詳しく

* [ログインスクリプトのテンプレート](/docs/ja-jp/authenticate/database-connections/custom-db/templates/login)
* [ユーザー取得スクリプトのテンプレート](/docs/ja-jp/authenticate/database-connections/custom-db/templates/get-user)
* [作成スクリプトのテンプレート](/docs/ja-jp/authenticate/database-connections/custom-db/templates/create)
* [スクリプトのテンプレートを削除する](/docs/ja-jp/authenticate/database-connections/custom-db/templates/delete)
* [パスワード変更スクリプトのテンプレート](/docs/ja-jp/authenticate/database-connections/custom-db/templates/change-password)
* [メール変更スクリプトのテンプレート](/docs/ja-jp/authenticate/database-connections/custom-db/templates/change-email)
