Skip to content

A custom authentication backend service built using Node.js, Express.js, MongoDB, and Mongoose, designed for enterprise-grade security and scalability featuring robust Access + Refresh Token-based authentication system, device-aware session tracking, OTP verification,support for multi-device login control. Architected using microservices principles

Notifications You must be signed in to change notification settings

YatharthKumarSaxena/Custom_Authentication_Service_NodeJS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“˜ Custom Authentication Service

Welcome to the Custom Authentication Service, a secure and scalable backend authentication system engineered using Node.js, Express.js, and MongoDB, designed with industry-grade practices such as Rate Limiting, Multi-Device Tracking, and Token Rotation (JWT). This project is structured with modularity, reusability, and production-readiness in mind, powered by real-world system design and software engineering principles.


๐Ÿงญ Table of Contents


๐Ÿ“– Introduction

This monolithic authentication backend is engineered to support:

  • Account creation & secure admin bootstrapping
  • Multi-device tracking via deviceID
  • Refresh and access token generation with custom expiry
  • Custom JWT validation middleware
  • Admin auto-creation at server start
  • Per-device rate limiting for brute-force prevention
  • Intelligent logging for each action (e.g., sign in, sign out, register)

The entry point for this project is server.js, where all major components are initialized including:

  • MongoDB connection
  • Admin account bootstrap
  • Centralized route mounting
  • Global error and 404 handling
  • Cron job triggers

๐Ÿงช Features

๐Ÿ”น Feature โœ… Implemented
Multi-Device Login Tracking โœ”๏ธ
JWT Token Generation & Rotation โœ”๏ธ
Rate Limiting per Device & Route โœ”๏ธ
Admin Auto-Creation at Startup โœ”๏ธ
Authentication Logs โœ”๏ธ
Centralized Error Handling โœ”๏ธ
Cookie Parser + JSON Body Parsing โœ”๏ธ
Cron Job Integration โœ”๏ธ
Intelligent 404 Rate Monitoring โœ”๏ธ
Device-Based Refresh Token Logic โœ”๏ธ

๐Ÿ”ง Tech Stack

  • Node.js: Runtime
  • Express.js: Web framework
  • MongoDB + Mongoose: NoSQL DB with schema modeling
  • JWT: Token-based authentication
  • dotenv: Environment config management
  • cookie-parser: For handling cookies
  • uuid: For generating deviceID

๐Ÿง  Design Principles & Patterns

โœ… Design Principles

Principle Full Form Usage
SOLID Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, Dependency Inversion Modular services, controllers, utils follow SRP
DRY Donโ€™t Repeat Yourself Reused logic across tokens, logging, error handlers
KISS Keep It Simple, Stupid Clear token logic, admin setup kept straightforward
YAGNI You Arenโ€™t Gonna Need It Avoided premature scaling or over-engineering

โœ… Design Patterns Used

Pattern Purpose
Singleton MongoDB connection, express server bootstrap
Factory Token generation utility with expiry injection
Template Method Used in log writing & token validation flow (extendable blueprint)
Observer (simulated) Setup ready for future log-subscriber or event-bus design

๐Ÿงฑ Folder Structure

๐Ÿ“ฆ Total 11 folders and 5 files are present in this project directory.

๐Ÿ“ Folders

Folder Name Description
๐Ÿ“ rate-limiters/ Device & route-specific rate limit services
๐Ÿ“ controllers/ Handles business logic for auth routes
๐Ÿ“ configs/ Configuration files for DB, server, tokens
๐Ÿ“ middlewares/ JWT auth, global error, malformed JSON etc.
๐Ÿ“ utils/ Utility functions like token creation, logs
๐Ÿ“ services/ Handles internal logic like limiter service
๐Ÿ“ routes/ Route entry-point for all modules
๐Ÿ“ models/ MongoDB schemas: User, Auth Logs
๐Ÿ“ cron-jobs/ Server-triggered tasks on boot
๐Ÿ“ internal-calls/ For internal microservice/API interaction
๐Ÿ“ node_modules/ Auto-installed dependencies (ignored in Git)

๐Ÿ“„ Files

File Name Description
server.js ๐ŸŽฏ Entry point โ€” starts DB, routes, admin
.env.example ๐ŸŒ Sample environment configuration
package.json ๐Ÿ“ฆ Project metadata and script definitions
package-lock.json ๐Ÿ”’ Locked dependency tree for consistent build
.gitignore ๐Ÿšซ Files/directories ignored in version control

๐Ÿ› ๏ธ Environment Variables

All sensitive credentials and project configurations are handled using environment variables. These variables are not committed for security reasons, but a complete structure is provided in the .env.example file.

Each environment variable plays a crucial role in how this service runs. Below is a breakdown of the major groups and their responsibilities:

๐Ÿ”น Server Configuration

Used to set the port on which the server will run locally or in production.

  • PORT_NUMBER

๐Ÿ”น MongoDB Database

Defines the local database name and MongoDB connection URI.

  • DB_NAME
  • DB_URL

๐Ÿ”น JWT Token System

Handles the secure issuance and expiry of both access and refresh tokens, including token rotation threshold.

  • ACCESS_TOKEN_SECRET_CODE
  • REFRESH_TOKEN_SECRET_CODE
  • ACCESS_TOKEN_EXPIRY
  • REFRESH_TOKEN_EXPIRY
  • REFRESH_THRESHOLD_IN_MS

๐Ÿ”น Bcrypt Password Hashing

Specifies the salt rounds used for secure password encryption.

  • SALT

๐Ÿ”น Admin User Bootstrap

At startup, the system auto-creates a default admin user using these credentials.

  • ADMIN_NAME
  • ADMIN_COUNTRY_CODE
  • ADMIN_NUMBER
  • ADMIN_FULL_PHONE_NUMBER
  • ADMIN_EMAIL_ID
  • ADMIN_PASSWORD (already hashed using bcrypt)
  • ADMIN_USER_ID

๐Ÿ”น System Infrastructure Settings

Used to define instance-specific capacity and IP-code logic.

  • IP_ADDRESS_CODE
  • USER_REGISTRATION_CAPACITY

๐Ÿ”น Cookie Policy

Sets client cookie behaviors for session management. Values should change between development and production environments.

  • COOKIE_HTTP_ONLY
  • COOKIE_SECURE
  • COOKIE_SAME_SITE
  • COOKIE_DOMAIN

๐Ÿ”น Device Identification (for Testing)

Used to simulate real-world testing with device-based rate limiting and refresh token storage.

  • DEVICE_UUID
  • DEVICE_TYPE
  • DEVICE_NAME

๐Ÿ”น Auth & User Cleanup Cron Jobs

These are automated scheduled tasks that run weekly to clean up outdated logs or inactive users.

  • AUTH_LOG_CLEANUP_CRON
  • AUTH_LOG_CLEANUP_TIMEZONE
  • AUTH_LOG_RETENTION_DAYS
  • USER_CLEANUP_CRON
  • USER_CLEANUP_TIMEZONE
  • USER_RETENTION_DAYS

๐Ÿ”น App Environment Mode

Defines the execution environment (development | production).

  • NODE_ENV

๐Ÿ“Œ Make sure to copy .env.example and rename it to .env before running the application. Fill in appropriate secrets and values as needed for your machine.


๐Ÿšฆ Rate Limiting Logic

This system implements device-based and route-specific rate limiting to prevent abuse, brute-force attacks, and excessive invalid requests.

๐Ÿ“Œ Highlights:

  • Every incoming request includes a deviceID (from request headers).
  • If the device is not recognized or is hitting unknown/unauthorized endpoints, itโ€™s still tracked.
  • Each device-route combination has its own limit logic.

๐Ÿง  How it Works:

  • Rate limit metadata is stored in MongoDB per device and route.
  • If a device crosses its threshold within a specific time window (e.g., 60 seconds), it is temporarily blocked.
  • The system sends a Retry-After header to inform clients when they can retry.
  • Smart logging ensures that no request gets dropped silently โ€” even invalid paths get monitored and tracked.

This also helps during attacks where bots attempt undefined endpoints to exploit the backend.


๐Ÿงช Testing Strategy

This project was thoroughly tested via Postman, ensuring real-world scenarios like:

๐Ÿ” Authentication Tests:

  • โœ… Registering a user with phone/email
  • โœ… Signing in on multiple devices
  • โœ… Logout from one or all devices
  • โœ… Token expiration and refresh

โš ๏ธ Security Tests:

  • โœ… Attempted login with wrong credentials
  • โœ… Tampered JWTs
  • โœ… Missing/Invalid deviceID in headers
  • โœ… Repeated requests to unauthorized endpoints

๐Ÿงช Behavior Tests:

  • โœ… Cron jobs triggering on time
  • โœ… Admin bootstrapping on server restart
  • โœ… Logs created and pruned as expected

In future, automated test suites (like Jest + Supertest) can be integrated for CI/CD pipelines.


๐Ÿงฌ Planned Enhancements

Even though the system is fully functional, the following improvements are under consideration for future versions:

๐Ÿ”ฎ Enhancement Priority Notes
Role-Based Access Control (RBAC) ๐Ÿ”บ High Allow role assignment to users (e.g., ADMIN, MODERATOR, USER)
OTP-Based Authentication ๐Ÿ”บ High Add SMS/Email-based OTPs for passwordless login
API Rate Limits per User Tier ๐Ÿ”ธ Medium Different limits for free vs. premium accounts
MongoDB Index Optimization ๐Ÿ”ธ Medium Speed up query performance and reduce latency
Test Automation ๐Ÿ”น Low Integrate with CI/CD for robust test coverage

๐ŸŽฏ Final Takeaway

This project reflects a deep understanding of authentication systems, production-level design thinking, and scalable backend engineering. The goal wasnโ€™t just to build an auth system, but to simulate the real-life challenges and decisions involved in developing a secure, intelligent, and maintainable authentication layer.

๐Ÿ’ก What Youโ€™ll Learn from This Repo:

  • How to issue and rotate secure JWTs
  • How to bootstrap admin users safely
  • How to scale multi-device login systems
  • How to implement custom rate limiting logic
  • How to structure Node.js projects with clean separation of concerns

๐Ÿ“ Feel free to clone, fork, or adapt this architecture to your own real-world applications.
Designed & Engineered by Yatharth Kumar Saxena ๐Ÿš€

About

A custom authentication backend service built using Node.js, Express.js, MongoDB, and Mongoose, designed for enterprise-grade security and scalability featuring robust Access + Refresh Token-based authentication system, device-aware session tracking, OTP verification,support for multi-device login control. Architected using microservices principles

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published