DEV Community

Puffer
Puffer

Posted on

# πŸ” Login Backend with Express, AWS Lambda and Dynamo DB

A robust, scalable backend API for authentication and user management built with Node.js and Express. Features secure login/signup, role-based access control, and seamless integration with AWS DynamoDB, Stripe, and Brevo.

✨ Features

  • πŸ” Authentication System - Secure user registration and login with JWT tokens
  • πŸ‘₯ Role-Based Access Control - Four-tier role system (User, Agent, Master, Super Admin)
  • πŸ”’ Password Security - Bcrypt password hashing for secure password storage
  • πŸ“Š DynamoDB Integration - NoSQL database operations with AWS DynamoDB
  • πŸ’³ Payment Processing - Stripe integration for payment handling
  • πŸ“§ Email Services - Brevo integration for email communications
  • πŸš€ Serverless Ready - Can be deployed as AWS Lambda function
  • πŸ›‘οΈ Security Middleware - JWT authentication and authorization middleware
  • πŸ“ Input Validation - Request validation for signup and login endpoints
  • πŸ—οΈ MVC Architecture - Clean separation of concerns with Models, Views, and Controllers

πŸ› οΈ Tech Stack

  • Runtime: Node.js
  • Framework: Express.js
  • Database: AWS DynamoDB
  • Authentication: JWT (JSON Web Tokens)
  • Password Hashing: bcryptjs
  • Payment: Stripe
  • Email: Brevo (formerly Sendinblue)
  • Deployment: Serverless (AWS Lambda compatible)

πŸ“‹ Prerequisites

Before you begin, ensure you have the following installed:

  • Node.js (v14 or higher)
  • npm or yarn
  • AWS Account (for DynamoDB)
  • Stripe Account (for payment processing)
  • Brevo Account (for email services)

πŸš€ Installation

  1. Clone the repository
   git clone https://github.com/puffer-git/login-dynamo-db.git
   cd login-dynamo-db
Enter fullscreen mode Exit fullscreen mode
  1. Install dependencies
   npm install
Enter fullscreen mode Exit fullscreen mode
  1. Set up environment variables

Create a .env file in the root directory with the following variables:

   # Server Configuration
   ENVIRONMENT=development
   PORT=4000

   # JWT Configuration
   JWT_SECRET=your-super-secret-jwt-key-change-this-in-production
   JWT_EXPIRES_IN=7d

   # AWS DynamoDB Configuration
   AWSREGION=us-east-1
   AWSENDPOINT=https://dynamodb.us-east-1.amazonaws.com
   AWSACCESSKEYID=your-aws-access-key-id
   AWSSECRETKEY=your-aws-secret-access-key

   # Stripe Configuration (optional)
   STRIPE_SECRET_KEY=your-stripe-secret-key

   # Brevo Configuration (optional)
   BREVO_API_KEY=your-brevo-api-key
Enter fullscreen mode Exit fullscreen mode
  1. Set up DynamoDB tables

Create a DynamoDB table named users with:

  • Partition Key: id (String)
  • Enable point-in-time recovery (recommended for production)

πŸƒ Running the Application

Development Mode

npm run dev
Enter fullscreen mode Exit fullscreen mode

The server will start on http://localhost:4000 with auto-reload enabled.

Production Mode

npm start
Enter fullscreen mode Exit fullscreen mode

Serverless Deployment

When ENVIRONMENT=production, the application exports a serverless handler for AWS Lambda deployment.

πŸ“š API Documentation

Base URL

  • Development: http://localhost:4000
  • Production: Your deployed endpoint

Authentication Endpoints

Register a New User

POST /auth/signup
Content-Type: application/json

{
  "player_name": "johndoe",
  "email": "john@example.com",
  "password": "securePassword123",
  "name": "John Doe" // optional
}
Enter fullscreen mode Exit fullscreen mode

Response (201 Created)

{
  "success": true,
  "message": "User created successfully",
  "data": {
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
Enter fullscreen mode Exit fullscreen mode

Error Responses

  • 409 Conflict - Player name or email already exists
  • 400 Bad Request - Validation error
  • 500 Internal Server Error - Server error

Login

POST /auth/login
Content-Type: application/json

{
  "identifier": "johndoe", // Can be email or player_name
  "password": "securePassword123"
}
Enter fullscreen mode Exit fullscreen mode

Response (200 OK)

{
  "success": true,
  "message": "Login successful",
  "data": {
    "user": {
      "role": "user",
      "player_name": "johndoe",
      "email": "john@example.com",
      "name": "John Doe"
    },
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
  }
}
Enter fullscreen mode Exit fullscreen mode

Error Responses

  • 401 Unauthorized - Invalid credentials
  • 400 Bad Request - Validation error
  • 500 Internal Server Error - Server error

Authentication Header

For protected routes, include the JWT token in the Authorization header:

Authorization: Bearer <your-jwt-token>
Enter fullscreen mode Exit fullscreen mode

πŸ—οΈ Project Structure

login-dynamo-db/
β”œβ”€β”€ app/
β”‚   β”œβ”€β”€ constants/
β”‚   β”‚   β”œβ”€β”€ roles.js          # Role definitions and hierarchy
β”‚   β”‚   └── tables.js         # DynamoDB table configurations
β”‚   β”œβ”€β”€ controllers/
β”‚   β”‚   └── auth/
β”‚   β”‚       β”œβ”€β”€ login/
β”‚   β”‚       β”‚   β”œβ”€β”€ login.js
β”‚   β”‚       β”‚   └── loginValidation.js
β”‚   β”‚       └── signup/
β”‚   β”‚           β”œβ”€β”€ signup.js
β”‚   β”‚           └── signupValidation.js
β”‚   β”œβ”€β”€ db/
β”‚   β”‚   β”œβ”€β”€ dynamoClient.js   # DynamoDB client configuration
β”‚   β”‚   └── index.js          # Database exports
β”‚   β”œβ”€β”€ middleware/
β”‚   β”‚   └── auth.js           # Authentication & authorization middleware
β”‚   β”œβ”€β”€ models/
β”‚   β”‚   β”œβ”€β”€ BaseModel.js      # Base model for DynamoDB operations
β”‚   β”‚   └── UserModel.js      # User model with business logic
β”‚   β”œβ”€β”€ routes/
β”‚   β”‚   β”œβ”€β”€ auth.js           # Authentication routes
β”‚   β”‚   └── index.js          # Route aggregator
β”‚   β”œβ”€β”€ utils/
β”‚   β”‚   └── userUtils.js      # User utility functions
β”‚   └── index.js              # Express app configuration
β”œβ”€β”€ index.js                   # Application entry point
β”œβ”€β”€ package.json
└── README.md
Enter fullscreen mode Exit fullscreen mode

πŸ” Role System

The application supports a four-tier role hierarchy:

  1. USER - Basic user role (default)
  2. AGENT - Agent-level permissions
  3. MASTER - Master-level permissions
  4. SUPER_ADMIN - Highest level of access

Roles are checked using middleware:

  • authenticate - Verifies JWT token
  • authorize(roles) - Checks if user has specific role(s)
  • requireMinimumRole(role) - Checks if user has minimum role level

πŸ§ͺ Development

Code Style

  • Follow existing code patterns
  • Use meaningful variable and function names
  • Add JSDoc comments for functions
  • Keep functions focused and single-purpose

Adding New Features

  1. Create feature branch: git checkout -b feature/your-feature-name
  2. Follow MVC architecture:
    • Models in app/models/
    • Controllers in app/controllers/
    • Routes in app/routes/
    • Middleware in app/middleware/
  3. Add validation for user inputs
  4. Write clear error messages
  5. Test your changes thoroughly
  6. Submit a pull request

🀝 Contributing

Contributions are welcome! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Contribution Guidelines

  • Write clear, readable code
  • Add comments for complex logic
  • Follow the existing code structure
  • Test your changes before submitting
  • Update documentation if needed

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ“§ Contact

Developer: Puffer

πŸ™ Acknowledgments

πŸ“„ License

MIT License - feel free to use this project for your own purposes!


⭐ If you find this project helpful, please consider giving it a star!

Top comments (0)