A comprehensive, secure, and scalable user authentication system built with Node.js, Express, and PostgreSQL. This API provides OAuth2 integration, JWT-based authentication, role-based access control, and extensive security features.
- JWT-based authentication with access and refresh tokens
- OAuth2 integration (Google, GitHub)
- Role-based access control (RBAC) with hierarchical permissions
- Email verification and password reset functionality
- Session management with device tracking
- Multi-provider authentication linking
- Rate limiting with Redis backend
- Input validation using Zod schemas
- Password strength requirements
- CSRF protection
- Security headers with Helmet.js
- IP blocking for suspicious activity
- SQL injection and XSS protection
- Profile management with avatar uploads
- User preferences system
- Account deletion with confirmation
- Session revocation (individual or all)
- OAuth provider management
- Comprehensive testing suite with Jest
- API documentation with detailed examples
- Docker support for containerization
- Environment-based configuration
- Structured logging
- Health checks and monitoring
- Node.js 16.0.0 or higher
- PostgreSQL 12.0 or higher
- Redis 6.0 or higher (for rate limiting)
- npm or yarn package manager
-
Clone the repository
git clone https://github.com/your-username/user-authentication-api.git cd user-authentication-api -
Install dependencies
npm install
-
Set up environment variables
cp .env.example .env # Edit .env with your configuration -
Set up the database
# Create database createdb auth_db # Run migrations npm run migrate
-
Start the application
# Development npm run dev # Production npm start
Create a .env file with the following variables:
# Database
DB_HOST=localhost
DB_PORT=5432
DB_NAME=auth_db
DB_USER=postgres
DB_PASSWORD=your_password
# JWT Secrets
JWT_ACCESS_SECRET=your_access_secret_here
JWT_REFRESH_SECRET=your_refresh_secret_here
# OAuth2
GOOGLE_CLIENT_ID=your_google_client_id
GOOGLE_CLIENT_SECRET=your_google_client_secret
GITHUB_CLIENT_ID=your_github_client_id
GITHUB_CLIENT_SECRET=your_github_client_secret
# Email
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=[email protected]
SMTP_PASS=your_app_password
# Security
SESSION_SECRET=your_session_secret_here
BCRYPT_ROUNDS=12
# Redis
REDIS_HOST=localhost
REDIS_PORT=6379http://localhost:3000
POST /auth/register
Content-Type: application/json
{
"email": "[email protected]",
"password": "securePassword123!",
"name": "John Doe",
"confirmPassword": "securePassword123!"
}POST /auth/login
Content-Type: application/json
{
"email": "[email protected]",
"password": "securePassword123!"
}GET /auth/me
Authorization: Bearer <access_token>GET /user/profile
Authorization: Bearer <access_token>PUT /user/profile
Authorization: Bearer <access_token>
Content-Type: application/json
{
"name": "Updated Name",
"bio": "Software developer"
}GET /oauth/googleGET /oauth/githubFor complete API documentation, see docs/API.md.
# Run all tests
npm test
# Run tests in watch mode
npm run test:watch
# Generate coverage report
npm run test:coverage
# Run specific test file
npm test -- tests/auth/auth.test.jsThe test suite includes:
- Unit tests for authentication endpoints
- Integration tests for user management
- Security tests for rate limiting and validation
- OAuth flow testing
-
Build and start services
docker-compose up -d
-
Run database migrations
docker-compose exec app npm run migrate -
View logs
docker-compose logs -f app
# Build image
docker build -t auth-api .
# Run container
docker run -p 3000:3000 --env-file .env auth-apiGET /healthResponse:
{
"status": "healthy",
"timestamp": "2023-01-01T00:00:00.000Z",
"uptime": 3600,
"database": "connected",
"redis": "connected"
}The application uses structured logging with different levels:
error: Error conditionswarn: Warning conditionsinfo: Informational messagesdebug: Debug information
Logs are written to:
- Console (development)
- Files (production)
- External services (configurable)
- JWT access tokens (1 hour expiry)
- Refresh tokens with rotation (7 days expiry)
- Secure token storage in database
- Token blacklisting on logout
- General API: 100 requests per 15 minutes
- Authentication: 10 requests per 15 minutes
- Password reset: 3 requests per hour
- Sensitive operations: 5 requests per 15 minutes
- All inputs validated using Zod schemas
- Protection against SQL injection and XSS
- File upload restrictions
- Email format validation
- Minimum 8 characters
- Complexity requirements
- Common password detection
- Bcrypt hashing with 12 rounds
For detailed deployment instructions, see docs/DEPLOYMENT.md.
# Install PM2
npm install -g pm2
# Start application
pm2 start ecosystem.config.js --env production
# Save PM2 configuration
pm2 save
# Setup startup script
pm2 startupProduction requires additional security considerations:
NODE_ENV=production
PORT=3000
CORS_ORIGIN=https://yourdomain.com
FRONTEND_URL=https://yourdomain.com- Fork the repository
- Create a feature branch
git checkout -b feature/amazing-feature
- Commit your changes
git commit -m 'Add amazing feature' - Push to the branch
git push origin feature/amazing-feature
- Open a Pull Request
- Follow the existing code style
- Add tests for new features
- Update documentation
- Ensure all tests pass
- Follow semantic versioning
This project is licensed under the MIT License - see the LICENSE file for details.
For support and questions:
- Create an issue on GitHub
- Check the documentation
- Review the API documentation
- Add more OAuth providers (Facebook, Twitter)
- Implement two-factor authentication
- Add user role management API
- Implement audit logging
- Add API rate limiting per user
- Create admin dashboard
- Add WebSocket support for real-time notifications
- Implement passwordless authentication
- Response time: < 100ms (average)
- Throughput: 1000+ requests/second
- Database optimization: Indexed queries
- Caching: Redis for rate limiting
- Compression: Gzip enabled
- Runtime: Node.js 18+
- Framework: Express.js
- Database: PostgreSQL 12+
- Cache: Redis 6+
- Authentication: JWT, Passport.js
- Validation: Zod
- Testing: Jest, Supertest
- Security: Helmet.js, bcrypt
- Documentation: Markdown
- Containerization: Docker
- Process Management: PM2
Built with β€οΈ for secure and scalable user authentication