Skip to content

Dave-code-creater/server

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

25 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Server API - Improved Architecture

This is a Node.js/Express server with improved architecture, better error handling, security features, and organized code structure.

πŸš€ Features

βœ… Architecture Improvements

  • Modular Structure: Better separation of concerns with organized folders
  • Configuration Management: Centralized configuration with environment validation
  • Error Handling: Custom error classes and comprehensive error middleware
  • Logging: Winston-based logging with file rotation and request tracking
  • Security: Helmet, rate limiting, CORS, and security headers
  • Database: Improved MongoDB connection management with retry logic
  • Authentication: Enhanced JWT-based auth with account locking and login attempts
  • Validation: Comprehensive input validation with Joi
  • API Versioning: Proper API versioning structure

πŸ”’ Security Features

  • Helmet for security headers
  • Rate limiting to prevent abuse
  • Account locking after failed login attempts
  • Password hashing with bcrypt
  • JWT token management with proper expiration
  • Input validation and sanitization
  • CORS configuration

πŸ“ Project Structure

server/
β”œβ”€β”€ config/                 # Configuration files
β”‚   β”œβ”€β”€ index.js           # Main configuration
β”‚   └── database.js        # Database connection manager
β”œβ”€β”€ controllers/           # Request handlers
β”‚   └── authController.js  # Authentication controller
β”œβ”€β”€ middleware/            # Custom middleware
β”‚   β”œβ”€β”€ index.js          # Middleware setup
β”‚   β”œβ”€β”€ auth.js           # Authentication middleware
β”‚   └── errorHandler.js   # Error handling middleware
β”œβ”€β”€ models/               # Database models
β”‚   └── User.js          # User model with enhanced features
β”œβ”€β”€ routes/              # Route definitions
β”‚   β”œβ”€β”€ index.js        # Main router
β”‚   β”œβ”€β”€ auth.js         # Authentication routes
β”‚   β”œβ”€β”€ users.js        # User routes
β”‚   β”œβ”€β”€ tasks.js        # Task routes
β”‚   └── companies.js    # Company routes
β”œβ”€β”€ utils/              # Utility functions
β”‚   β”œβ”€β”€ errors.js       # Custom error classes
β”‚   β”œβ”€β”€ logger.js       # Logging configuration
β”‚   └── jwt.js          # JWT service
β”œβ”€β”€ validators/         # Input validation
β”‚   └── authValidator.js # Authentication validation
β”œβ”€β”€ logs/              # Log files (auto-created)
β”œβ”€β”€ index.js           # Main server file
└── package.json       # Dependencies and scripts

πŸ› οΈ Installation & Setup

  1. Install Dependencies

    npm install
  2. Environment Configuration Create a .env file in the root directory:

    # Server Configuration
    NODE_ENV=development
    PORT=6000
    
    # Database Configuration
    MONGO_URI=mongodb://localhost:27017/your-database-name
    DB_NAME=your-database-name
    
    # JWT Configuration
    ACCESS_TOKEN_SECRET=your-super-secret-access-token-key-here
    REFRESH_TOKEN_SECRET=your-super-secret-refresh-token-key-here
    ACCESS_TOKEN_EXPIRY=15m
    REFRESH_TOKEN_EXPIRY=7d
    
    # Security Configuration
    BCRYPT_ROUNDS=12
    
    # Rate Limiting
    RATE_LIMIT_WINDOW_MS=900000
    RATE_LIMIT_MAX=100
    
    # CORS Configuration
    CORS_ORIGIN=https://www.danhsachcongviec.site
    
    # Logging Configuration
    LOG_LEVEL=info
    LOG_FILE=logs/app.log
  3. Start the Server

    # Development mode
    npm run dev
    
    # Production mode
    npm start

πŸ“š API Documentation

Base URL

  • Development: http://localhost:6000
  • API Version: /api/v1

Health Check

  • GET /health - Server health status

Authentication Endpoints

  • POST /api/v1/auth/register - Register new user
  • POST /api/v1/auth/login - User login
  • POST /api/v1/auth/refresh-token - Refresh access token
  • POST /api/v1/auth/logout - User logout (requires auth)
  • GET /api/v1/auth/me - Get current user profile (requires auth)
  • PATCH /api/v1/auth/update-password - Update password (requires auth)
  • POST /api/v1/auth/verify-token - Verify token validity (requires auth)

Example Requests

Register User

curl -X POST http://localhost:6000/api/v1/auth/register \
  -H "Content-Type: application/json" \
  -d '{
    "username": "johndoe",
    "email": "john@example.com",
    "password": "SecurePass123!",
    "confirmPassword": "SecurePass123!"
  }'

Login User

curl -X POST http://localhost:6000/api/v1/auth/login \
  -H "Content-Type: application/json" \
  -d '{
    "email": "john@example.com",
    "password": "SecurePass123!"
  }'

πŸ”§ Key Improvements Made

1. Configuration Management

  • Centralized configuration in config/index.js
  • Environment variable validation
  • Database connection management with retry logic

2. Error Handling

  • Custom error classes for different error types
  • Comprehensive error middleware with proper logging
  • Development vs production error responses

3. Security Enhancements

  • Account locking after failed login attempts
  • Rate limiting to prevent abuse
  • Security headers with Helmet
  • Enhanced password validation
  • JWT token management improvements

4. Logging System

  • Winston-based logging with file rotation
  • Request tracking with unique request IDs
  • Different log levels for different environments
  • Structured logging with metadata

5. Database Improvements

  • Connection pooling and retry logic
  • Graceful shutdown handling
  • Enhanced User model with validation
  • Proper indexing for performance

6. Code Organization

  • Better separation of concerns
  • Modular middleware setup
  • Clean controller architecture
  • Proper route organization with versioning

7. Validation System

  • Comprehensive input validation with Joi
  • Custom validation messages
  • Middleware-based validation

πŸš€ Development Scripts

npm run dev      # Start development server with nodemon
npm start        # Start production server
npm test         # Run tests (to be implemented)
npm run lint     # Run linting (to be implemented)
npm run build    # Build process (to be implemented)

πŸ“ Logging

Logs are automatically created in the logs/ directory:

  • app.log - All application logs
  • error.log - Error logs only

In development mode, logs are also displayed in the console with colors.

πŸ”’ Security Features

  1. Rate Limiting: 100 requests per 15 minutes per IP
  2. Account Locking: Account locked for 2 hours after 5 failed login attempts
  3. Password Security: Strong password requirements with bcrypt hashing
  4. JWT Security: Proper token expiration and validation
  5. Headers Security: Helmet middleware for security headers
  6. Input Validation: Comprehensive validation for all inputs

🀝 Contributing

  1. Follow the existing code structure
  2. Add proper error handling
  3. Include logging for important operations
  4. Write validation for new endpoints
  5. Update documentation

πŸ“„ License

This project is licensed under the ISC License.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published