AWSCognito User Pool

Cognito UserPoolでアクティベーションしたタイミングでWelcomeメールを送る

Cognito UserPoolにはトリガーが用意されており、任意のタイミングでLambdaを実行することができます。 「確認後」のトリガーにLambdaをセットすることで、アカウントの有効化が実行されたタイミングでメー […]

広告ここから
広告ここまで

Cognito UserPoolにはトリガーが用意されており、任意のタイミングでLambdaを実行することができます。

「確認後」のトリガーにLambdaをセットすることで、アカウントの有効化が実行されたタイミングでメールを送るという機能をつけることができます。

コードサンプル

module.exports.handler = (event, context, callback) => {
  const email = event.request.userAttributes.email
  const params = {
    Destination: {
      ToAddresses: [ email ]
    },
    Message: {
      Body: {
        Text: {
          Charset: 'UTF-8',
          Data: `Hello ${event.userName} \nWelcome to our service!`
        }
      },
      Subject: {
        Charset: 'UTF-8',
        Data: 'Welcome !'
      }
    },
    ReplyToAddresses: [
      'info@example.com'
    ],
    Source: 'noreply@example.com'
  }
  ses.sendEmail(params).promise()
  .then(result => callback(null, event))
  .catch(err => callback('Fail to send email'))
}

Tips:IAM Roleの設定を忘れずに

Lambdaからses:SendEmailが実行できるようにIAMロールの設定をしておきましょう。

Serverless Frameworkの場合は以下のように書けばOKです。

provider:
  name: aws
  runtime: nodejs6.10
  timeout: 30
  stage: development

  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "ses:SendEmail"
      Resource:
        - "arn:aws:ses:*:*:identity/noreply@example.com"
...

もちろん、SESで登録済みのアドレスしか使えないのでご注意ください。

ローカルでテストする

これのテストのために毎回アクティベーション作業をするのもなかなか大変です。
幸いなことにAWSのドキュメントにトリガーから実行された場合のeventの値が記載されていますので、それを使ってテストしましょう。

{
  "version": 1,
  "triggerSource": "PostAuthentication_Authentication",
  "region": "<region>",
  "userPoolId": "<userPoolId>",
  "userName": "<userName>",
  "callerContext": {
      "awsSdk": "<calling aws sdk with version>",
      "clientId": "<apps client id>",
      ...
  },
  "request": {
      "userAttributes": {
          "phone_number_verified": true,
          "email_verified": true,
          "email": "hoge@example.com",
          ... //all custom attributes
      }
  },
  "response": {}
}

via: 認証後の例 > サンプルイベントパラメータ

Serverless Frameworkを使っている場合は、sls invoke localでテストできます。

$ sls invoke local -f postConfirmation -d '{
  "version": 1,
  "triggerSource": "PostAuthentication_Authentication",
  "region": "<region>",
  "userPoolId": "<userPoolId>",
  "userName": "<userName>",
  "callerContext": {
      "awsSdk": "<calling aws sdk with version>",
      "clientId": "<apps client id>",
  },
  "request": {
      "userAttributes": {
          "phone_number_verified": true,
          "email_verified": true,
          "email": "hoge@example.com"
      }
  },
  "response": {}
}'

ブックマークや限定記事(予定)など

WP Kyotoサポーター募集中

WordPressやフロントエンドアプリのホスティング、Algolia・AWSなどのサービス利用料を支援する「WP Kyotoサポーター」を募集しています。
月額または年額の有料プランを契約すると、ブックマーク機能などのサポーター限定機能がご利用いただけます。

14日間のトライアルも用意しておりますので、「このサイトよく見るな」という方はぜひご検討ください。

広告ここから
広告ここまで

Related Category posts