

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 註冊前 Lambda 觸發程序
<a name="user-pool-lambda-pre-sign-up"></a>

您可能想要在具有自助註冊選項的使用者集區中自訂註冊程序。預先註冊觸發程序的一些常見用途是執行新使用者的自訂分析和記錄、套用安全性和控管標準，或將第三方 IdP 的使用者連結至[合併的使用者設定檔](cognito-user-pools-identity-federation-consolidate-users.md)。您可能也有不需要進行[驗證和確認](signing-up-users-in-your-app.md)的信任使用者。

在 Amazon Cognito 完成建立新的[本機](cognito-terms.md#terms-localuser)或[聯合身分](cognito-terms.md#terms-federateduser)使用者之前，它會啟用註冊前 Lambda 函數。傳送至此函數之請求物件`userAttributes`中的 包含本機使用者註冊所提供的屬性，或已成功從聯合身分使用者的提供者屬性映射的屬性。您的使用者集區會在使用 [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) 進行自助註冊時叫用此觸發，或使用受信任[身分提供者](amazon-cognito-user-pools-authentication-flow-methods.md#amazon-cognito-user-pools-authentication-flow-methods-federated)首次登入，以及使用 [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) 建立使用者時叫用此觸發。在註冊過程中，您可以使用此函數來分析具有自訂邏輯的登入事件，以及修改或拒絕新使用者。

**Topics**
+ [註冊前 Lambda 觸發程序參數](#cognito-user-pools-lambda-trigger-syntax-pre-signup)
+ [註冊前範例：自動確認來自已註冊網域的使用者](#aws-lambda-triggers-pre-registration-example)
+ [註冊前範例：自動確認及自動驗證所有使用者](#aws-lambda-triggers-pre-registration-example-2)
+ [註冊前範例：如果使用者名稱少於五個字元，則拒絕註冊](#aws-lambda-triggers-pre-registration-example-3)

## 註冊前 Lambda 觸發程序參數
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup"></a>

Amazon Cognito 傳遞至此 Lambda 函數的請求，是以下參數和 Amazon Cognito 新增至所有請求的[常用參數](https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-pools-working-with-lambda-triggers.html#cognito-user-pools-lambda-trigger-syntax-shared)之組合。

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "string": "string",
            . . .
        },
        "validationData": {
            "string": "string",
            . . .
         },
        "clientMetadata": {
            "string": "string",
            . . .
         }
    },

    "response": {
        "autoConfirmUser": "boolean",
        "autoVerifyPhone": "boolean",
        "autoVerifyEmail": "boolean"
    }
}
```

------

### 註冊前請求參數
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-request"></a>

**userAttributes**  
代表使用者屬性的一或多組名稱/值。屬性名稱是索引鍵。

**validationData**  
您的應用程式在建立新使用者的請求中傳遞給 Amazon Cognito 的一或多個鍵值對與使用者屬性資料。在 [AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html) 或 [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html) API 請求的 ValidationData 參數中，將此資訊傳送至 Lambda 函數。  
Amazon Cognito 不會將您的 ValidationData 資料設定為您建立之使用者的屬性。ValidationData 是您為了預先註冊 Lambda 觸發程式而提供的臨時使用者資訊。

**clientMetadata**  
您可以做為 Lambda 函數的自訂輸入提供的一個或多個鍵值組，該函數是您用於註冊前觸發程序所指定。您可以使用下列 API 動作中的 ClientMetadata 參數，將此資料傳遞至您的 Lambda 函數：[AdminCreateUser](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html)、[AdminRespondToAuthChallenge](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminRespondToAuthChallenge.html)、[ForgotPassword](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ForgotPassword.html) 和 [SignUp](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_SignUp.html)。

### 註冊前回應參數
<a name="cognito-user-pools-lambda-trigger-syntax-pre-signup-response"></a>

如果您想要自動確認使用者，可以在回應中將 `autoConfirmUser`設定為 `true`。您可以將 `autoVerifyEmail`設定為 `true`，以自動驗證使用者的電子郵件。您可以將 `autoVerifyPhone`設定為 `true`，以自動驗證使用者的電話號碼。

**注意**  
`AdminCreateUser` API 觸發尚未註冊的 Lambda 函數時，Amazon Cognito 會忽略回應參數 `autoVerifyPhone`、`autoVerifyEmail` 和 `autoConfirmUser`。

**autoConfirmUser**  
設定為 `true`以自動確認使用者，否則設定為 `false`。

**autoVerifyEmail**  
設定為 `true` 以設定為已驗證註冊使用者的電子郵件地址，否則設定為 `false`。如果 `autoVerifyEmail`設定為 `true`，`email` 屬性必須包含有效的非 null 值。否則會發生錯誤，而且使用者將無法完成註冊。  
如果選取 `email` 屬性做為別名，則在設定 `autoVerifyEmail` 時，將會為使用者的電子郵件地址建立別名。如果使用該電子郵件地址的別名已存在，則會將別名移至新使用者，而舊使用者的電子郵件地址會標記為未驗證。如需詳細資訊，請參閱[自訂登入屬性](user-pool-settings-attributes.md#user-pool-settings-aliases)。

**autoVerifyPhone**  
設定為 `true`以設定為已驗證註冊使用者的電話號碼，否則設定為 `false`。如果 `autoVerifyPhone`設定為 `true`，`phone_number` 屬性必須包含有效的非 null 值。否則會發生錯誤，而且使用者將無法完成註冊。  
如果選取 `phone_number`屬性做為別名，則在設定 `autoVerifyPhone` 時，將會為使用者的電話號碼建立別名。如果使用該電話號碼的別名已存在，則會將別名移至新使用者，而舊使用者的電話號碼會標記為未驗證。如需詳細資訊，請參閱[自訂登入屬性](user-pool-settings-attributes.md#user-pool-settings-aliases)。

## 註冊前範例：自動確認來自已註冊網域的使用者
<a name="aws-lambda-triggers-pre-registration-example"></a>

這是範例 Lambda 觸發程式碼。在 Amazon Cognito 處理註冊請求之前，會立即叫用註冊前觸發條件。它會使用自訂屬性 **custom:domain**，自動確認來自特定電子郵件網域的新使用者。不在自訂網域中的任何新使用者都會新增到這個使用者集區，但不會自動確認。

------
#### [ Node.js ]

```
export const handler = async (event, context, callback) => {
  // Set the user pool autoConfirmUser flag after validating the email domain
  event.response.autoConfirmUser = false;

  // Split the email address so we can compare domains
  var address = event.request.userAttributes.email.split("@");

  // This example uses a custom attribute "custom:domain"
  if (event.request.userAttributes.hasOwnProperty("custom:domain")) {
    if (event.request.userAttributes["custom:domain"] === address[1]) {
      event.response.autoConfirmUser = true;
    }
  }

  // Return to Amazon Cognito
  callback(null, event);
};
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    # It sets the user pool autoConfirmUser flag after validating the email domain
    event['response']['autoConfirmUser'] = False

    # Split the email address so we can compare domains
    address = event['request']['userAttributes']['email'].split('@')

    # This example uses a custom attribute 'custom:domain'
    if 'custom:domain' in event['request']['userAttributes']:
        if event['request']['userAttributes']['custom:domain'] == address[1]:
            event['response']['autoConfirmUser'] = True

    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito 會將事件資訊傳遞至您的 Lambda 函數。此函數會將相同事件物件傳回 Amazon Cognito，並在回應中附上任何變更。在 Lambda 主控台中，您可使用與 Lambda 觸發程序相關聯的資料來設定測試事件。下列是此程式碼範例的測試事件：

------
#### [ JSON ]

```
{
    "request": {
        "userAttributes": {
            "email": "testuser@example.com",
            "custom:domain": "example.com"
        }
    },
    "response": {}
}
```

------

## 註冊前範例：自動確認及自動驗證所有使用者
<a name="aws-lambda-triggers-pre-registration-example-2"></a>

此範例會確認所有使用者並設定使用者的 `email` 和 `phone_number` 屬性以驗證屬性是否存在。此外，如果啟用別名，則當設定自動驗證時，將會為 `phone_number`和 `email` 建立別名。

**注意**  
如果使用相同電話號碼的別名已存在，則會將別名移至新使用者，而舊使用者的 `phone_number`會標記為未驗證。電子郵件地址也是一樣。若要防止發生這種情況，您可以使用這些使用者集區[ListUsers API](https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_ListUsers.html)，查看是否有現有的使用者已經使用新使用者的電話號碼或電子郵件地址做為別名。

------
#### [ Node.js ]

```
exports.handler = (event, context, callback) => {
  // Confirm the user
  event.response.autoConfirmUser = true;

  // Set the email as verified if it is in the request
  if (event.request.userAttributes.hasOwnProperty("email")) {
    event.response.autoVerifyEmail = true;
  }

  // Set the phone number as verified if it is in the request
  if (event.request.userAttributes.hasOwnProperty("phone_number")) {
    event.response.autoVerifyPhone = true;
  }

  // Return to Amazon Cognito
  callback(null, event);
};
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    # Confirm the user
    event['response']['autoConfirmUser'] = True

    # Set the email as verified if it is in the request
    if 'email' in event['request']['userAttributes']:
        event['response']['autoVerifyEmail'] = True

    # Set the phone number as verified if it is in the request
    if 'phone_number' in event['request']['userAttributes']:
        event['response']['autoVerifyPhone'] = True

    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito 會將事件資訊傳遞至您的 Lambda 函數。此函數會將相同事件物件傳回 Amazon Cognito，並在回應中附上任何變更。在 Lambda 主控台中，您可使用與 Lambda 觸發程序相關聯的資料來設定測試事件。下列是此程式碼範例的測試事件：

------
#### [ JSON ]

```
{
  "request": {
    "userAttributes": {
      "email": "user@example.com",
      "phone_number": "+12065550100"
    }
  },
  "response": {}
}
```

------

## 註冊前範例：如果使用者名稱少於五個字元，則拒絕註冊
<a name="aws-lambda-triggers-pre-registration-example-3"></a>

此範例會檢查註冊請求中的使用者名稱長度。如果使用者輸入的名稱長度少於五個字元，則範例會傳回錯誤。

------
#### [ Node.js ]

```
export const handler = (event, context, callback) => {
    // Impose a condition that the minimum length of the username is 5 is imposed on all user pools.
    if (event.userName.length < 5) {
        var error = new Error("Cannot register users with username less than the minimum length of 5");
        // Return error to Amazon Cognito
        callback(error, event);
    }
    // Return to Amazon Cognito
    callback(null, event);
};
```

------
#### [ Python ]

```
def lambda_handler(event, context):
    if len(event['userName']) < 5:
        raise Exception("Cannot register users with username less than the minimum length of 5")
    # Return to Amazon Cognito
    return event
```

------

Amazon Cognito 會將事件資訊傳遞至您的 Lambda 函數。此函數會將相同事件物件傳回 Amazon Cognito，並在回應中附上任何變更。在 Lambda 主控台中，您可使用與 Lambda 觸發程序相關聯的資料來設定測試事件。下列是此程式碼範例的測試事件：

------
#### [ JSON ]

```
{
  "userName": "rroe",
  "response": {}
}
```

------