A production-grade authentication backend built with TypeScript, Node.js, Express.js, MongoDB, Redis, JWT tokens, and industry-standard security best practices.
- User Registration with email verification (6-digit OTP)
- User Login with JWT access tokens (15 min expiry) and refresh tokens (30 days)
- Secure Token Rotation - Old refresh tokens are revoked when new ones are issued
- Email Verification using OTP stored in Redis
- Password Reset with OTP-based verification
- Logout with token revocation
- bcrypt password hashing with configurable salt rounds
- JWT access and refresh tokens with secure rotation
- Redis for fast OTP and token storage
- Helmet for HTTP security headers
- Rate Limiting to prevent brute-force attacks
- CORS configuration
- Input Sanitization and validation with Joi
- NoSQL Injection Prevention with express-mongo-sanitize
- HTTP-only Cookies for refresh tokens
- Secure Cookie Settings (SameSite, Secure flags)
- Role-Based Access Control with three roles:
user,admin,superadmin - Protected Routes with role-based middleware
- Admin Dashboard with user management
- Nodemailer integration for email sending
- Professional HTML Email Templates for verification and password reset
- 6-digit OTP for email verification and password reset
- TypeScript for type safety and better developer experience
- Soft Delete for user accounts
- Pagination for admin user lists
- Winston Logging with file and console outputs
- Morgan HTTP request logging
- Global Error Handler with detailed error messages
- Standardized API Responses
- Swagger/OpenAPI Documentation
- Comprehensive Test Suite with Jest and Supertest
- MVC Architecture with clean code organization
/auth-master-node
βββ /config
β βββ database.ts # MongoDB connection
β βββ email.ts # Email configuration
β βββ redis.ts # Redis configuration
β βββ security.ts # Security settings
β βββ swagger.ts # Swagger/OpenAPI config
βββ /controllers
β βββ authController.ts # Authentication logic
β βββ adminController.ts # Admin operations
βββ /services
β βββ authService.ts # Business logic for auth
β βββ emailService.ts # Email sending service
β βββ tokenService.ts # JWT token management
β βββ redisOTPService.ts # OTP management with Redis
β βββ redisTokenService.ts # Token storage in Redis
βββ /models
β βββ User.ts # User schema with Mongoose
β βββ RefreshToken.ts # Refresh token schema
β βββ OTP.ts # OTP schema
βββ /routes
β βββ authRoutes.ts # Auth endpoints
β βββ adminRoutes.ts # Admin endpoints
βββ /middleware
β βββ authMiddleware.ts # JWT validation
β βββ roleMiddleware.ts # RBAC authorization
β βββ errorHandler.ts # Global error handler
β βββ rateLimiter.ts # Rate limiting
β βββ validator.ts # Input validation
βββ /utils
β βββ responseFormatter.ts # Standard responses
β βββ logger.ts # Winston logger
β βββ validators.ts # Joi schemas
β βββ helpers.ts # Utility functions
βββ /types
β βββ index.ts # TypeScript type definitions
βββ /tests
β βββ auth.test.ts # Authentication tests
β βββ admin.test.ts # Admin endpoint tests
β βββ setup.ts # Test configuration
β βββ README.md # Testing guide
β βββ TEST_RESULTS.md # Test results
βββ /logs # Log files (auto-generated)
βββ /dist # Compiled JavaScript (auto-generated)
βββ server.ts # Entry point
βββ tsconfig.json # TypeScript configuration
βββ jest.config.js # Jest test configuration
βββ .env.example # Environment template
βββ .env.test.example # Test environment template
βββ .gitignore
βββ package.json
βββ README.md
- Node.js (v16 or higher)
- MongoDB (local or MongoDB Atlas)
- Redis (local or Redis Cloud)
- Gmail Account (for SMTP) or other email service
git clone <repository-url>
cd auth-master-nodenpm installCreate a .env file in the root directory by copying .env.example:
cp .env.example .envEdit .env and configure the following:
# Server Configuration
NODE_ENV=development
PORT=5000
# Database Configuration
MONGODB_URI=mongodb://localhost:27017/robust-auth-db
# For MongoDB Atlas:
# MONGODB_URI=mongodb+srv://username:password@cluster.mongodb.net/robust-auth-db
# Redis Configuration
REDIS_HOST=localhost
REDIS_PORT=6379
REDIS_PASSWORD=
# JWT Configuration
JWT_ACCESS_SECRET=your-super-secret-access-token-key
JWT_REFRESH_SECRET=your-super-secret-refresh-token-key
JWT_ACCESS_EXPIRY=15m
JWT_REFRESH_EXPIRY=30d
# Bcrypt Configuration
BCRYPT_SALT_ROUNDS=12
# Email Configuration (Gmail)
EMAIL_HOST=smtp.gmail.com
EMAIL_PORT=587
EMAIL_SECURE=false
EMAIL_USER=your-email@gmail.com
EMAIL_PASSWORD=your-app-specific-password
EMAIL_FROM=noreply@yourapp.com
# OTP Configuration
OTP_EXPIRY_MINUTES=10
# Cookie Configuration
COOKIE_SECRET=your-cookie-secret-key
# CORS Configuration
CORS_ORIGIN=http://localhost:3000
# Application URLs
APP_URL=http://localhost:5000
FRONTEND_URL=http://localhost:3000- Enable 2-Factor Authentication on your Gmail account
- Generate an App Password: https://myaccount.google.com/apppasswords
- Use the generated password in
EMAIL_PASSWORD
Development Mode (with hot-reloading):
npm run devBuild TypeScript:
npm run buildProduction Mode:
npm startType Checking (without building):
npm run type-checkThe server will start on http://localhost:5000
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Run tests with coverage
npm run test:coverage- β 21 Authentication endpoint tests
- β 17 Admin endpoint tests
- β Full RBAC testing
- β OTP verification flow
- β Token refresh and rotation
- β Password reset flow
See tests/README.md for detailed testing documentation.
| Method | Endpoint | Description | Access |
|---|---|---|---|
| POST | /api/auth/register |
Register new user | Public |
| POST | /api/auth/login |
Login user | Public |
| POST | /api/auth/logout |
Logout user | Public |
| POST | /api/auth/refresh-token |
Refresh access token | Public |
| POST | /api/auth/verify-email |
Verify email with OTP | Public |
| POST | /api/auth/forgot-password |
Request password reset | Public |
| POST | /api/auth/reset-password |
Reset password with OTP | Public |
| GET | /api/auth/me |
Get current user profile | Private |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /api/admin/stats |
Get dashboard statistics | Admin |
| GET | /api/admin/users |
Get all users (paginated) | Admin |
| GET | /api/admin/users/:id |
Get user by ID | Admin |
| PUT | /api/admin/users/:id |
Update user details | Admin |
| DELETE | /api/admin/users/:id |
Soft delete user | Admin |
| POST | /api/admin/users/:id/restore |
Restore deleted user | Admin |
| Method | Endpoint | Description | Access |
|---|---|---|---|
| GET | /health |
Health check | Public |
| GET | /api-docs |
Swagger documentation | Public |
| GET | /api-docs.json |
OpenAPI JSON spec | Public |
POST /api/auth/register
Content-Type: application/json
{
"name": "John Doe",
"email": "john@example.com",
"phone": "1234567890",
"password": "SecurePass123!",
"role": "user"
}Response:
{
"success": true,
"message": "Registration successful. Please check your email for verification OTP.",
"data": {
"user": {
"_id": "...",
"name": "John Doe",
"email": "john@example.com",
"role": "user",
"isVerified": false
}
}
}POST /api/auth/verify-email
Content-Type: application/json
{
"email": "john@example.com",
"otp": "123456"
}POST /api/auth/login
Content-Type: application/json
{
"email": "john@example.com",
"password": "SecurePass123!"
}Response:
{
"success": true,
"message": "Login successful",
"data": {
"user": { ... },
"accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...",
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
}GET /api/auth/me
Authorization: Bearer <access_token>POST /api/auth/refresh-token
Content-Type: application/json
{
"refreshToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}GET /api/admin/users?page=1&limit=10&role=user&search=john
Authorization: Bearer <admin_access_token>Interactive API documentation is available via Swagger UI:
Local Development: http://localhost:5000/api-docs
The documentation includes:
- All endpoint descriptions
- Request/response schemas
- Authentication requirements
- Example requests and responses
- Try-it-out functionality
-
Password Security
- Bcrypt hashing with configurable salt rounds
- Strong password requirements (min 8 chars, uppercase, lowercase, number, special char)
- Password never returned in API responses
-
Token Security
- Short-lived access tokens (15 minutes)
- Long-lived refresh tokens (30 days) stored in Redis
- Secure token rotation on refresh
- Tokens revoked on logout
- Token blacklisting support
-
HTTP Security
- Helmet for security headers
- CORS with specific origin configuration
- Rate limiting on sensitive endpoints
- NoSQL injection prevention
- Request size limits
-
Cookie Security
- HTTP-only cookies
- Secure flag in production
- SameSite attribute
- Signed cookies
-
Input Validation
- Joi validation on all inputs
- Sanitization to prevent XSS
- Email format validation
- Type safety with TypeScript
-
Error Handling
- No sensitive data in error messages
- Different messages for dev/production
- Comprehensive logging
- Global error handler
-
TypeScript Benefits
- Compile-time type checking
- Better IDE support and autocomplete
- Reduced runtime errors
- Self-documenting code
Logs are stored in the /logs directory:
error.log- Error-level logscombined.log- All logsexceptions.log- Uncaught exceptionsrejections.log- Unhandled promise rejections
npm run buildThis compiles TypeScript to JavaScript in the dist/ directory.
- Set
NODE_ENV=production - Use strong, unique secrets for JWT and cookies
- Configure MongoDB Atlas connection string
- Configure Redis Cloud or ElastiCache
- Set up proper CORS origins
- Use HTTPS for secure cookies
- Backend: Heroku, Railway, Render, DigitalOcean, AWS
- Database: MongoDB Atlas
- Cache: Redis Cloud, AWS ElastiCache
- Email: SendGrid, AWS SES, or Gmail SMTP
The project uses strict TypeScript settings in tsconfig.json:
- Strict type checking enabled
- ES2020 target
- ESNext modules
- Source maps for debugging
Some files use // @ts-nocheck for gradual migration. To improve types:
- Remove
// @ts-nocheckfrom a file - Add proper type annotations
- Fix any type errors
- Test thoroughly
MIT License
Built with β€οΈ using TypeScript, Node.js, Express, MongoDB, and Redis
Contributions are welcome! Please feel free to submit a Pull Request.
For issues or questions, please open an issue on GitHub.
- Add email queue with Bull
- Add 2FA authentication
- Add OAuth integration (Google, GitHub)
- Add WebSocket support for real-time notifications
- Add GraphQL API
- Improve test coverage to 100%
- Add performance monitoring
- Add API versioning