An open API service indexing awesome lists of open source software.

https://github.com/ksingh1817/session-auth-express-mongo

Cred & Session-based authentication using Express & mongoDB
https://github.com/ksingh1817/session-auth-express-mongo

authentication authorization compression cors ejs express-rate-limit express-validator expressjs hashedpassword helmetjs login-system mongodb mongodb-atlas mongoose mvc-architecture nodemailer otp-verification swagger swagger-api swagger-ui

Last synced: about 2 months ago
JSON representation

Cred & Session-based authentication using Express & mongoDB

Awesome Lists containing this project

README

          

๐Ÿงพ 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