AWS COGNITO: How to implement Post Confirmation Trigger which works only after SignupConfirmation not after ForgotPassword/ResetPassword Confirmation

Viewed 3517

Someone can please tell me, that how can send this mail after the Post Confirmation of Signup only. This code is sending mail after every confirmation whether it is forget password/reset password or Signup.

var aws = require('aws-sdk');

var ses = new aws.SES();

exports.handler = (event, context, callback) => {
    console.log(event);

    if (event.request.userAttributes.email) {
            sendEmail(event.request.userAttributes.email, "Congratulations " + event.userName + ", you have been confirmed: ", function(status) {

            // Return to Amazon Cognito
            callback(null, event);
        });
    } else {
        // Nothing to do, the user's email ID is unknown
        callback(null, event);
    }
};

function sendEmail(to, body, completedCallback) {
    var eParams = {
        Destination: {
            ToAddresses: [to]
        },
        Message: {
            Body: {
                Text: {
                    Data: body
                }
            },
            Subject: {
                Data: "Cognito Identity Provider registration completed"
            }
        },

        // Replace source_email with your SES validated email address
        Source: "<source_email>"
    };

    var email = ses.sendEmail(eParams, function(err, data){
        if (err) {
            console.log(err);
        } else {
            console.log("===EMAIL SENT===");
        }
        completedCallback('Email sent');
    });
    console.log("EMAIL CODE END");
};
1 Answers

You can check triggerSource attribute of the event object.

Post Confirmation of Signup event will have trigger source is PostConfirmation_ConfirmSignUp

Your handle function will look like this:

exports.handler = (event, context, callback) => {
  console.log(event);

  if (
    event.request.userAttributes.email
    && event.triggerSource === "PostConfirmation_ConfirmSignUp") {
    sendEmail(event.request.userAttributes.email, "Congratulations " + event.userName + ", you have been confirmed: ", function (status) {

      // Return to Amazon Cognito
      callback(null, event);
    });
  } else {
    // Nothing to do, the user's email ID is unknown
    callback(null, event);
  }
};

Reference: User Pool Lambda Trigger Sources

Related