Skip to content

ksingh1817/session-auth-express-mongo

Repository files navigation

🧾 Project Overview

This web application is a secure and scalable user management system built with Express.js, MongoDB Atlas, and Mongoose, following the MVC (Model-View-Controller) architecture. It features robust authentication, role-based access control, session management, and user-friendly CRUD operations.
The app is designed with a focus on security, maintainability, and user experience. It includes critical functionality like email-based OTP verification, password reset, image upload and processing, and soft deletion (activate/deactivate users).

🔐 Authentication

  • Session-Based Authentication: Managed with express-session and connect-mongo for persistent sessions stored in MongoDB
  • Email & Password Login: Secure credential handling with Bcrypt password hashing
  • Email OTP Verification: Enforced for both user registration and password reset workflows
  • Secure Routing: Custom middleware protects sensitive routes and resources
  • Role-Based Access Control (RBAC): Fine-grained access for user, admin, and superadmin roles

👤 User Management

  • User Registration: Sign up with email-based OTP verification to ensure valid user identities
  • Secure Login: Session-based authentication with encrypted credentials
  • Forgot Password: Password reset workflow using OTP sent via email
  • OTP Verification: Required before completing registration or resetting passwords
  • Controls: Admins/Superadmin can create new users and manage existing accounts
  • Profile Management: Users can update their personal and account details
  • Soft Deletion: Toggle user activation status without permanently deleting data
  • User Directory: View all users with pagination, sorting, and filtering options
  • Profile Picture Upload: Upload and auto-resize profile images using Multer and Sharp

📄 API & Documentation - Swagger

  • Interactive Documentation: Explore and test API endpoints directly from the browser
  • Auto-Generated Specs: OpenAPI-based docs generated from route definitions
  • Authentication Support: Easily test secured endpoints using auth headers (e.g., sessions or tokens)
  • Schema Validation: Ensures request and response formats match the defined API contract

🔎 Logging & Monitoring – Winston

  • Structured Logging: Logs are categorized by severity levels (info, warn, error) for better traceability
  • Log Filtering: Easily view logs based on severity and date to aid in debugging and analysis
  • Audit-Ready Exports: Download logs in .csv format for compliance, reporting, or audit purposes

📘 Architecture: MVC Pattern

The application follows the Model-View-Controller (MVC) architectural pattern to promote separation of concerns, improve maintainability, and support scalable development.

  • Model: Defines data structures and business rules using Mongoose schemas (e.g., User, OTP)
  • View: Server-rendered UI using EJS templates for displaying data and forms to the user
  • Controller: Handles application logic, processes incoming requests, manages authentication, and coordinates between Models and Views

🧠 Performance Optimization – Redis Cloud Integration

To enhance application performance and reduce database load, Redis Cloud has been integrated using the ioredis client. This enables fast, in-memory caching for frequently accessed routes data.

  • Dynamic Caching: Responses are cached using unique keys based on query parameters (e.g., pagination, sorting, filtering) to ensure accurate results for different requests.
  • Automatic TTL: Cached data automatically expires based on the CACHE_TTL environment variable, keeping the cache fresh and relevant.
  • Manual Invalidation: Cache entries are cleared when user data is updated/deleted/activated/deactivated to maintain consistency.
  • Setup: Define REDIS_HOST, REDIS_PORT, and REDIS_PASSWORD in your environment config.

⚠️ Using Redis Cloud Free Tier (trial account) – may have connection/resource limits.

✅ Testing (Coming Soon)

Testing is in progress and will use Node's built-in node:test module for unit and integration testing without external libraries.

🧰 Tech Stack

⚙️ Deployment Tools

  • GitHub – Source code management, version control, and collaboration
  • Render.com – Cloud hosting platform for deploying and scaling Express.js applications
  • MongoDB Atlas – Fully managed, cloud-based NoSQL database with built-in scalability and high availability
  • Redis Cloud – In-memory caching (via ioredis) to optimize performance for frequently accessed routes

📦 Backend Technologies

  • Express.js – Minimal and flexible Node.js web application framework for building APIs and server-side logic
  • MongoDB Atlas – Cloud-hosted, highly scalable NoSQL database with built-in monitoring and security features
  • Mongoose – Elegant MongoDB object modeling (ODM) library for defining schemas and managing data relationships
  • EJS – Lightweight templating engine for rendering dynamic server-side HTML views
  • caching – Robust ioredis client for implementing in-memory caching and improving response performance

🔐 Security

  • Bcrypt – Secure password hashing with salting to protect user credentials
  • express-session – Manages user sessions on the server side
  • connect-mongo – Persists session data in MongoDB for scalability and reliability
  • express-rate-limit – Limits repeated requests to APIs, mitigating brute-force and denial-of-service attacks
  • Helmet – Sets various HTTP headers to safeguard against common web vulnerabilities (XSS, clickjacking, etc.)
  • CORS – Enables secure, cross-origin resource sharing with fine-grained control

📑 Validation

  • Zod – Type-safe schema validation for incoming data
  • deep-email-validator – Deep email validation for real addresses

📧 Email & OTP

  • Nodemailer – SMTP-based email sending (e.g., for OTPs)
  • Twilio – SMS Notification on success registation/password changed/forget password. (trial account - self only)

📁 File Upload & Image Processing

  • Multer – Handles file uploads (e.g., profile pictures)
  • Sharp – Image resizing, compression, format conversion

📦 Performance

  • compression – Enables Gzip/Brotli compression for faster load times

🛡️ Future-Proofing

This application is built with extensibility in mind, allowing for easy integration of additional features and technologies as the project evolves.

  • Cloud Storage for Images: Integration with services like Cloudinary, Firebase Storage, or AWS S3 for scalable image hosting
  • JWT Authentication: Support for stateless API authentication using JSON Web Tokens
  • Refresh Tokens: Secure token renewal mechanism for long-lived sessions
  • Multi-Factor Authentication (MFA): Additional layer of login security via email, SMS, or authenticator apps
  • Custom Email Templates: Use of MJML or SendGrid for responsive and branded transactional emails
  • Automated Testing: Integration with testing frameworks like Jest or Mocha/Chai for unit and integration testing