|
| 1 | +use aws_config::BehaviorVersion; |
| 2 | +use aws_lambda_events::event::cognito::CognitoEventUserPoolsPostConfirmation; |
| 3 | +use aws_sdk_ses::{ |
| 4 | + types::{Body, Content, Destination, Message}, |
| 5 | + Client, |
| 6 | +}; |
| 7 | +use lambda_runtime::{run, service_fn, tracing, Error, LambdaEvent}; |
| 8 | + |
| 9 | +const SOURCE_EMAIL: &str = "<source_email>"; |
| 10 | + |
| 11 | +async fn function_handler( |
| 12 | + client: &aws_sdk_ses::Client, |
| 13 | + event: LambdaEvent<CognitoEventUserPoolsPostConfirmation>, |
| 14 | +) -> Result<CognitoEventUserPoolsPostConfirmation, Error> { |
| 15 | + let payload = event.payload; |
| 16 | + |
| 17 | + if let Some(email) = payload.request.user_attributes.get("email") { |
| 18 | + let body = if let Some(name) = payload.request.user_attributes.get("name") { |
| 19 | + format!("Welcome {name}, you have been confirmed.") |
| 20 | + } else { |
| 21 | + "Welcome, you have been confirmed.".to_string() |
| 22 | + }; |
| 23 | + send_post_confirmation_email(client, email, "Cognito Identity Provider registration completed", &body).await?; |
| 24 | + } |
| 25 | + |
| 26 | + // Cognito always expect a response with the same shape as |
| 27 | + // the event when it handles Post Confirmation triggers. |
| 28 | + Ok(payload) |
| 29 | +} |
| 30 | + |
| 31 | +async fn send_post_confirmation_email(client: &Client, email: &str, subject: &str, body: &str) -> Result<(), Error> { |
| 32 | + let destination = Destination::builder().to_addresses(email).build(); |
| 33 | + let subject = Content::builder().data(subject).build()?; |
| 34 | + let body = Content::builder().data(body).build()?; |
| 35 | + |
| 36 | + let message = Message::builder() |
| 37 | + .body(Body::builder().text(body).build()) |
| 38 | + .subject(subject) |
| 39 | + .build(); |
| 40 | + |
| 41 | + client |
| 42 | + .send_email() |
| 43 | + .source(SOURCE_EMAIL) |
| 44 | + .destination(destination) |
| 45 | + .message(message) |
| 46 | + .send() |
| 47 | + .await?; |
| 48 | + |
| 49 | + Ok(()) |
| 50 | +} |
| 51 | + |
| 52 | +#[tokio::main] |
| 53 | +async fn main() -> Result<(), Error> { |
| 54 | + tracing::init_default_subscriber(); |
| 55 | + |
| 56 | + let config = aws_config::load_defaults(BehaviorVersion::latest()).await; |
| 57 | + let client = Client::new(&config); |
| 58 | + |
| 59 | + run(service_fn(|event| function_handler(&client, event))).await |
| 60 | +} |
0 commit comments