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.
- ๐ Introduction
- ๐งช Features
- ๐ง Tech Stack
- ๐ง Design Principles & Patterns
- ๐งฑ Folder Structure
- ๐ ๏ธ Environment Variables
- ๐ฆ Rate Limiting Logic
- ๐งช Testing Strategy
- ๐งฌ Planned Enhancements
- ๐ฏ Final Takeaway
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
๐น 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 | โ๏ธ |
- 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
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 |
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 |
๐ฆ Total 11 folders and 5 files are present in this project directory.
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) |
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 |
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:
Used to set the port on which the server will run locally or in production.
PORT_NUMBER
Defines the local database name and MongoDB connection URI.
DB_NAME
DB_URL
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
Specifies the salt rounds used for secure password encryption.
SALT
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
Used to define instance-specific capacity and IP-code logic.
IP_ADDRESS_CODE
USER_REGISTRATION_CAPACITY
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
Used to simulate real-world testing with device-based rate limiting and refresh token storage.
DEVICE_UUID
DEVICE_TYPE
DEVICE_NAME
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
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.
This system implements device-based and route-specific rate limiting to prevent abuse, brute-force attacks, and excessive invalid requests.
- 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.
- 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.
This project was thoroughly tested via Postman, ensuring real-world scenarios like:
- โ Registering a user with phone/email
- โ Signing in on multiple devices
- โ Logout from one or all devices
- โ Token expiration and refresh
- โ Attempted login with wrong credentials
- โ Tampered JWTs
- โ Missing/Invalid deviceID in headers
- โ Repeated requests to unauthorized endpoints
- โ 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.
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 |
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.
- 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 ๐