DEV Community

Cover image for Building CloudRegNotify: An AWS-Based User Registration and Notification System
richard ndemo
richard ndemo

Posted on

Building CloudRegNotify: An AWS-Based User Registration and Notification System

In today's digital age, user registration and notification systems play a critical role in enhancing user experience and engagement. I embarked on a journey to create CloudRegNotify, a scalable cloud-based system leveraging various AWS services to automate user sign-up, verify email addresses, store user data securely, and send notifications. This project not only challenged my skills but also deepened my understanding of cloud architecture.

Project Overview

The primary goal of CloudRegNotify was to build an efficient system that simplifies user registration while ensuring data security and scalability. By automating the user sign-up process and utilizing AWS services, I aimed to create a seamless experience for users.

Architecture

To achieve this, I designed the architecture of CloudRegNotify to incorporate the following AWS services:

AWS Cognito: For user authentication and management.
AWS Lambda: To handle the user registration logic and backend processing.
DynamoDB: For securely storing user information.
Amazon SNS: To send email notifications to users.

Image description

Implementation Steps
The implementation process was divided into several key steps, each presenting unique challenges.

Step 1: Creating a Cognito User Pool

I started by creating a user pool in the AWS Cognito console, configuring it to require both an email and a username for sign-in while enabling email verification. Ensuring the correct configuration of the user pool was crucial, as any oversight could lead to significant issues later.

Image description

Step 2: Setting Up DynamoDB
Next, I created a DynamoDB table named "UserPreferences" to store user data. Initially, I faced challenges designing an efficient table schema but opted for a straightforward structure for this Minimum Viable Product (MVP).

Image description

Step 3: Configuring SNS
To send notifications, I created an SNS topic called "UserNotifications." Configuring permissions for Lambda to interact with SNS was initially tricky, but I managed to troubleshoot and resolve the issues.

Image description

Step 4: Lambda Function Creation
I developed a Lambda function named "NotificationHandler" using Python. Writing the logic for storing user details in DynamoDB and triggering SNS notifications required several iterations, especially when I encountered permission errors. Updating the execution role with the correct policies resolved these issues.

import json
import boto3
import logging

# Initialize logging
logging.basicConfig(level=logging.INFO)

# Initialize DynamoDB and SNS clients
dynamodb = boto3.resource('dynamodb')
sns = boto3.client('sns')

def lambda_handler(event, context):
    logging.info("Received event: %s", json.dumps(event))

    try:
        user_id = event['userName']
        email = event['request']['userAttributes']['email']

        logging.info(f"User confirmed: {user_id}, Email: {email}")

        # Access DynamoDB Table
        table = dynamodb.Table('UserPreferences')

        # Store user details in DynamoDB
        table.put_item(
            Item={
                'UserID': user_id,
                'Email': email,
                'NotificationPreference': 'Email'
            }
        )
        logging.info("User details saved to DynamoDB")

        # Subscribe the user's email to the SNS topic
        try:
            sns.subscribe(
                TopicArn='arn:aws:sns:us-east-1:867093160463:UserNotifications',  # Replace with your SNS Topic ARN
                Protocol='email',
                Endpoint=email
            )
            logging.info(f"User {email} subscribed to SNS topic")
        except Exception as sub_error:
            logging.error(f"Error subscribing user {email} to SNS topic: {str(sub_error)}")
            # You can choose to continue or return here if you don't want the process to continue.
            # return event

        # Send notification via SNS
        message = f"Hello {user_id}, your account has been successfully created!"
        response = sns.publish(
            TopicArn='arn:aws:sns:us-east-1:867093160463:UserNotifications',  # Replace with your SNS Topic ARN
            Message=message,
            Subject="Account Created"
        )
        logging.info("SNS publish response: %s", response)

        # Return the event as required by Cognito Post Confirmation trigger
        return event

    except Exception as e:
        logging.error("Error occurred: %s", str(e))
        return {
            'statusCode': 500,
            'body': json.dumps(f"An error occurred: {str(e)}")
        }

Enter fullscreen mode Exit fullscreen mode

Image description

Functionality

Once the setup was complete, I rigorously tested the system to ensure its functionality:

User Registration: Users can register with their email and username.
Email Verification: A verification code is sent to users, and upon confirmation, their details are securely stored in DynamoDB.
Notification: A welcome email is sent via SNS once the account is created.

AWS Services Used

The successful implementation of CloudRegNotify relied on several AWS services:

  • AWS Cognito
  • AWS Lambda
  • DynamoDB
  • Amazon SNS

Challenges and Solutions

Throughout the project, I faced various challenges, including:

Setting Permissions: Figuring out why my Lambda function couldn’t publish to SNS or write to DynamoDB was frustrating. I resolved this by attaching the necessary policies, enabling seamless interaction between services.
Handling Event Errors: ** I encountered issues with subscriptions to the SNS topic due to invalid email addresses. By enhancing error logging, I ensured that invalid emails wouldn’t disrupt the entire process.
**Testing:
Comprehensive testing revealed multiple bugs, such as notifications not triggering correctly. Leveraging AWS CloudWatch logs proved invaluable for debugging.

Future Improvements

Reflecting on this project, I have identified several enhancements I plan to implement:

User Preferences: Allow users to select their preferred notification method (email, SMS, or push notifications).
Improved Error Handling: Develop more robust mechanisms to handle edge cases, particularly during user subscriptions.
Analytics: Introduce analytics to track user engagement with notifications, providing insights for improving user experience.

Conclusion

Building CloudRegNotify has been a rewarding learning experience. By leveraging AWS services like Lambda, Cognito, DynamoDB, and SNS, I created a scalable, cloud-based solution for user registration and notifications. The challenges I encountered allowed me to deepen my understanding of AWS, and I am proud of the system I developed.

You can explore the project further on GitHub.

Top comments (0)