β‘ Security Status: 33% improvement (50/100 β 83/100).
ποΈ System Architecture Overview
π― Core Design Principles
π Reusability
Single authentication service powers multiple frontend applications, eliminating code duplication and
ensuring consistency.
β‘ Performance
Asynchronous email processing ensures users don't wait for email delivery, improving response times.
π‘οΈ Security
JWT RS256 encryption, bcrypt password hashing, rate limiting, and secure cookie handling.
π Scalability
Event-driven architecture with AWS services allows horizontal scaling and reliable message
processing.
Key Innovation: This architecture demonstrates system thinking by implementing a
centralized authentication system with event-driven background processing.
βοΈ Technical Specifications
Technology Stack
Node.js 18+
Express.js
MongoDB
JWT (RS256)
AWS SNS/SQS
AWS Lambda
Docker
Google OAuth 2.0
GitHub Actions
ποΈ Architecture Patterns Implemented
Microservices Architecture
Single-responsibility service handling authentication for multiple client applications with clear
service boundaries.
Event-Driven Design
Asynchronous message processing using AWS SNS/SQS for decoupled email notifications.
Repository Pattern
Clean separation between data access layer and business logic with dedicated service and controller
layers.
Configuration Management
Environment-based configuration with secure secrets management and different settings for dev/prod.
π§ System Configuration
Authentication Methods:
- Traditional: Email/password with bcrypt hashing (12 salt rounds)
- OAuth: Google OAuth 2.0 integration
Security Implementation:
- JWT Configuration: RS256 asymmetric encryption, 12-hour expiration
- Rate Limiting: 10 requests per 5 minutes for auth endpoints
- Cookie Security: httpOnly, secure, sameSite protection
- CORS: Multi-origin support for production applications
π³ Deployment Architecture
Containerization:
- Multi-stage Docker builds for optimized image size
- Non-root user execution for security
- Health checks for container monitoring
- Separate development and production configurations
CI/CD Pipeline:
- GitHub Actions for automated testing
- ESLint for code quality assurance
- Multi-version Node.js testing (18.x, 20.x, 22.x)
π Key Features & Design Decisions
Authentication Features
π Dual Authentication
Traditional & OAuth: Supports both email/password and Google OAuth 2.0, providing
flexibility for different user preferences.
πͺ Cookie-Based Sessions
Secure & Persistent: Migrated from localStorage to secure httpOnly cookies, solving
data persistence and security issues.
π« JWT Token Management
RS256 Encryption: Asymmetric key signing for enhanced security with 12-hour
expiration time.
π¦ Rate Limiting
DDoS Protection: Configurable request limiting to prevent abuse and ensure service
availability.
π§ Background Processing Architecture
Design Decision: Implemented asynchronous email processing to prevent user experience
degradation. Users receive immediate authentication response while email notifications are processed in the
background.
Email Processing Flow:
- Event Publication: Auth service publishes user events to AWS SNS topic
- Message Filtering: SQS queues receive filtered messages based on event type
- Lambda Processing: AWS Lambda functions triggered by SQS messages
- Email Delivery: Lambda functions handle email sending
ποΈ Code Organization & Best Practices
Project Structure Design:
- Modular Architecture: Separate folders for users, OAuth, middleware, and utilities
- Configuration Management: Centralized config files for different environments
- Middleware Pattern: Reusable middleware for rate limiting, logging, and validation
- Service Layer: Business logic separated from route handlers
π‘οΈ Security Design Decisions
Password Security
Bcrypt hashing with salt rounds, secure password validation.
Token Security
RSA-256 asymmetric encryption, proper key management, and 12-hour token expiration.
Request Security
Input validation, CORS protection, rate limiting.
Data Security
Secure cookie configuration, environment variable management, and proper error message handling.
β οΈ Known Limitations
Current System Constraints:
- Token Management: No refresh token strategy implemented yet - users must
re-authenticate after token expiration (12 hours)
- Performance Metrics: Limited performance benchmarks and load testing data available
- Observability: Basic logging implemented but lacks comprehensive monitoring and
alerting
πΊοΈ Roadmap & Future Enhancements
β‘ Active Development - Prioritized by Impact & Timeline:
High Priority (January 2025):
- TypeScript Migration: Full type safety across codebase, strict TypeScript configuration with ESNext features, enhanced IDE support and maintainability
- Integration Testing: Jest + Supertest framework, comprehensive test coverage for authentication flows, automated testing in CI/CD pipeline
- Redis Caching: Connection pooling configuration, session storage optimization, cache invalidation strategies for improved performance
Medium Priority (February 2025):
- API Documentation: Swagger/OpenAPI specification, interactive API explorer at /api-docs, request/response examples with authentication flows
- Active Winston Logging: Replace console.log with structured JSON logging throughout application, context-aware logging with request IDs, environment-specific log levels
Future Enhancements:
- Token Lifecycle Management: Refresh token implementation (1-hour access token + 7-day refresh token), token rotation strategy for enhanced security
- Two-Factor Authentication: TOTP-based 2FA with QR code generation for optional enhanced security
System Evolution: This service evolved from localStorage-based session management (with
data persistence issues) to secure cookie-based authentication, solving real-world production problems
encountered in previous projects.
π API Endpoints & Integration Guide
Authentication Endpoints
POST
/api/users/signup
Purpose: Register new user with email/password
Required Fields: name, email, password, username, business
Response: JWT token set as httpOnly cookie + user data
Events: Triggers 'user_registered' SNS message for welcome email
POST
/api/users/login
Purpose: Authenticate existing user
Required Fields: email, password, business
Response: JWT token set as httpOnly cookie + user data
Events: Triggers 'user_loggedIn' SNS message for login notification
POST
/api/users/logout
Purpose: Clear user session and invalidate token
Response: Success confirmation with cookie cleared
OAuth Endpoints
GET
/api/auth/google/callback
Purpose: Google OAuth 2.0 callback handler
Process: Receives Google auth code, exchanges for user data
Response: JWT token set as httpOnly cookie + redirect to frontend
GET
/api/auth/google/verify
Purpose: Verify JWT token validity
Response: Token status and user information
π Integration Examples
Frontend Integration Pattern:
// Login Request Example
fetch('https://yourdomain.com/api/users/login', {
method: 'POST',
credentials: 'include', // Important for cookies
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: 'user@example.com',
password: 'password123',
business: 'resource-manager'
})
})
ποΈ Configuration Requirements
Frontend CORS Configuration:
- Each client application must be added to CORS origins
- Supports multiple development and production URLs
- Environment-specific configuration management
Cookie Domain Settings:
- Production: Domain-specific cookie settings
- Development: Localhost-compatible configuration
- Cross-subdomain support for multiple applications
Integration Benefits: One-time integration effort provides authentication for unlimited
client applications. Each new frontend requires only CORS configuration update, no code changes needed.
π Production Usage & Performance Metrics
Current Production Applications
Purpose: Developer resource management system
Features: Multi-link bookmarks, document uploads, tag-based search, organized collections
Authentication: Email/password and Google OAuth integration
Purpose: Book rental and management platform
Features: Catalog browsing, cart management, wishlist functionality, user profiles
Authentication: Seamless single sign-on across platform
π Deployment & Infrastructure
Current Infrastructure:
- Hosting: VPS deployment with Docker containerization
- Database: MongoDB Atlas for reliability and automatic backups
- Email Processing: AWS (SNS, SQS, Lambda) for scalable asynchronous messaging
- SSL/TLS: Let's Encrypt certificates with automatic renewal
Cost Optimization:
- VPS vs AWS: 70% cost reduction while maintaining performance
- Shared Services: Single auth service reduces infrastructure duplication
- Efficient Resources: Optimized Docker images and resource allocation
π‘ Key Learnings & Insights
Evolution Journey: From localStorage session management issues to production-ready
cookie-based authentication with event-driven architecture. Each challenge solved contributed to a more
robust, scalable system.
Technical Insights:
- Microservices Benefits: Code reusability, independent deployment, technology
flexibility
- Async Processing: Significant UX improvement by not blocking user interactions
- Security First: Implementing security from ground up vs retrofitting
- Infrastructure Decisions: Cost vs complexity trade-offs in cloud vs VPS deployment