Skip to content

Latest commit

Β 

History

History
361 lines (274 loc) Β· 9.96 KB

File metadata and controls

361 lines (274 loc) Β· 9.96 KB

FreelancerFlow - Production-Ready Backend

License Node.js MongoDB Express Tests Coverage

A production-ready, enterprise-grade REST API for freelancers to manage clients, projects, time logs, invoices, payments, and expenses.

πŸš€ Features

Core Functionality

  • βœ… Authentication & Authorization - JWT-based auth with Role-Based Access Control and Firebase Social Auth (Google/GitHub) support.
  • βœ… Client Management - Full CRUD operations for client data
  • βœ… Project Tracking - Hourly and fixed-price billing support
  • βœ… Time Logging - Track billable and non-billable hours
  • βœ… Invoice Generation - Professional PDF invoices with automatic calculations
  • βœ… Payment Tracking - Record and monitor payments
  • βœ… Expense Management - Track business expenses
  • βœ… Reporting & Analytics - Financial reports and insights
  • βœ… Notifications - Real-time notification system
  • βœ… Admin Dashboard - Administrative controls and metrics

Security Features

  • πŸ”’ Input Sanitization - Protection against NoSQL injection and XSS
  • πŸ”’ Rate Limiting - Configurable rate limits per endpoint type
  • πŸ”’ Helmet.js - Security headers and CSP
  • πŸ”’ CORS - Whitelist-based origin control
  • πŸ”’ JWT Authentication - Secure token-based authentication
  • πŸ”’ Password Hashing - Bcrypt with configurable rounds
  • πŸ”’ HPP Protection - HTTP Parameter Pollution prevention

Production Features

  • πŸ“Š Comprehensive Logging - Winston with log rotation
  • πŸ“Š Error Tracking - Structured error handling
  • πŸ“Š API Documentation - Swagger/OpenAPI 3.0
  • πŸ“Š Health Checks - Monitoring endpoints
  • πŸ“Š Graceful Shutdown - Proper cleanup on termination
  • πŸ“Š Environment Validation - Required config checks on startup

Testing & Quality

  • βœ… Unit Tests - Comprehensive test coverage
  • βœ… Integration Tests - API endpoint testing
  • βœ… CI/CD Pipeline - GitHub Actions automation
  • βœ… Code Coverage - 70%+ coverage requirement
  • βœ… Security Audits - Automated vulnerability scanning

πŸ“‹ Prerequisites

  • Node.js >= 18.x
  • MongoDB >= 6.0
  • npm >= 9.x

πŸ› οΈ Installation

1. Clone the repository

```bash git clone https://github.com/Rajkoli145/FreelancerFlow.git cd FreelancerFlow/backend ```

2. Install dependencies

```bash npm install ```

3. Environment Configuration

Create a `.env` file in the backend directory:

```bash cp .env.example .env ```

Required Environment Variables:

```env

Server

NODE_ENV=development PORT=5000

Database

MONGO_URI=mongodb://localhost:27017/freelancerflow

Authentication (REQUIRED - Generate secure key)

JWT_SECRET=your_super_secret_jwt_key_min_32_chars_CHANGE_THIS JWT_EXPIRE=7d

Frontend

FRONTEND_URL=http://localhost:5173

Security

BCRYPT_ROUNDS=10

Features

ENABLE_SWAGGER=true ```

Generate a secure JWT secret:

```bash node -e "console.log(require('crypto').randomBytes(64).toString('hex'))" ```

4. Start MongoDB

```bash

Using Docker

docker run -d -p 27017:27017 --name mongodb mongo:6.0

Or use your local MongoDB installation

mongod ```

5. Run the application

```bash

Development mode with auto-reload

npm run dev

Production mode

npm start ```

The server will start on http://localhost:5000

πŸ“š API Documentation

Once the server is running, access the interactive API documentation:

Swagger UI: http://localhost:5000/api-docs

OpenAPI JSON: http://localhost:5000/api-docs.json

πŸ§ͺ Testing

```bash

Run all tests with coverage

npm test

Run tests in watch mode

npm run test:watch

Run only unit tests

npm run test:unit

Run only integration tests

npm run test:integration

Run tests for CI/CD

npm run test:ci ```

πŸ” Code Quality

```bash

Run linter

npm run lint

Fix linting issues

npm run lint:fix ```

πŸ“ Project Structure

``` backend/ β”œβ”€β”€ src/ β”‚ β”œβ”€β”€ config/ # Configuration files β”‚ β”‚ β”œβ”€β”€ config.js # Environment config with validation β”‚ β”‚ β”œβ”€β”€ db.js # Database connection β”‚ β”‚ └── swagger.js # API documentation setup β”‚ β”œβ”€β”€ controllers/ # Request handlers β”‚ β”‚ β”œβ”€β”€ authController.js β”‚ β”‚ β”œβ”€β”€ clientController.js β”‚ β”‚ β”œβ”€β”€ projectController.js β”‚ β”‚ └── ... β”‚ β”œβ”€β”€ middleware/ # Custom middleware β”‚ β”‚ β”œβ”€β”€ authMiddleware.js # JWT authentication β”‚ β”‚ β”œβ”€β”€ errorMiddleware.js # Error handling β”‚ β”‚ └── validateMiddleware.js # Input validation β”‚ β”œβ”€β”€ models/ # Mongoose schemas β”‚ β”‚ β”œβ”€β”€ user.js β”‚ β”‚ β”œβ”€β”€ Client.js β”‚ β”‚ β”œβ”€β”€ Project.js β”‚ β”‚ └── ... β”‚ β”œβ”€β”€ routes/ # API routes β”‚ β”‚ β”œβ”€β”€ authRoutes.js β”‚ β”‚ β”œβ”€β”€ clientRoutes.js β”‚ β”‚ └── ... β”‚ β”œβ”€β”€ utils/ # Utility functions β”‚ β”‚ β”œβ”€β”€ logger.js # Winston logger β”‚ β”‚ β”œβ”€β”€ errors.js # Custom error classes β”‚ β”‚ └── pdfGenerator.js # Invoice PDF generation β”‚ β”œβ”€β”€ tests/ # Test files β”‚ β”‚ β”œβ”€β”€ setup/ β”‚ β”‚ └── *.test.js β”‚ └── index.js # Application entry point β”œβ”€β”€ logs/ # Application logs (auto-generated) β”œβ”€β”€ coverage/ # Test coverage reports β”œβ”€β”€ .env.example # Environment variables template β”œβ”€β”€ jest.config.json # Jest configuration └── package.json ```

πŸ” Security Best Practices

Implemented Security Measures

  1. No Hardcoded Secrets - All sensitive data in environment variables
  2. Input Validation - Joi schemas for all API inputs
  3. SQL/NoSQL Injection Protection - express-mongo-sanitize
  4. XSS Protection - xss-clean middleware
  5. Rate Limiting - Configurable per endpoint type
  6. CORS - Whitelist-based origin control
  7. Security Headers - Helmet.js with CSP
  8. Error Sanitization - No sensitive data in error responses
  9. Logging - Structured logging without sensitive data
  10. Dependency Audits - Regular npm audit checks

Security Checklist for Production

  • Generate strong JWT secret (64+ characters)
  • Set NODE_ENV=production
  • Use HTTPS only
  • Configure proper CORS origins
  • Set up firewall rules
  • Enable MongoDB authentication
  • Use environment-specific rate limits
  • Set up monitoring and alerting
  • Regular security audits
  • Keep dependencies updated

πŸš€ Deployment

Environment Variables for Production

```env NODE_ENV=production PORT=5000 MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/freelancerflow JWT_SECRET=<64-character-random-string> FRONTEND_URL=https://your-frontend-domain.com RATE_LIMIT_MAX_REQUESTS=50 ENABLE_SWAGGER=false ```

Deployment Platforms

Heroku

```bash heroku create your-app-name heroku config:set NODE_ENV=production heroku config:set MONGO_URI=your_mongodb_uri heroku config:set JWT_SECRET=your_jwt_secret git push heroku main ```

Railway

```bash railway login railway init railway up ```

AWS EC2 / DigitalOcean

  1. Set up Node.js environment
  2. Install PM2: npm install -g pm2
  3. Start application: pm2 start src/index.js --name freelancerflow
  4. Configure nginx as reverse proxy
  5. Set up SSL with Let's Encrypt

πŸ“Š Monitoring

Health Check Endpoints

  • Basic Health: GET /health
  • API Health: GET /api/health

Logs

Logs are stored in logs/ directory:

  • combined-YYYY-MM-DD.log - All logs
  • error-YYYY-MM-DD.log - Error logs only
  • exceptions-YYYY-MM-DD.log - Uncaught exceptions
  • rejections-YYYY-MM-DD.log - Unhandled promise rejections

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Write tests for new features
  • Maintain 70%+ code coverage
  • Follow existing code style
  • Update documentation
  • Add JSDoc comments for functions

πŸ“ API Endpoints

Authentication

  • POST /api/auth/signup - Register new user
  • POST /api/auth/login - Login user
  • GET /api/auth/me - Get current user
  • PUT /api/auth/profile - Update profile
  • PUT /api/auth/password - Change password
  • POST /api/auth/firebase - Login/Signup with Firebase OAuth (Google/GitHub)

Clients

  • GET /api/client - List all clients
  • POST /api/client - Create client
  • GET /api/client/:id - Get client details
  • PUT /api/client/:id - Update client
  • DELETE /api/client/:id - Delete client

Projects

  • GET /api/project - List all projects
  • POST /api/project - Create project
  • GET /api/project/:id - Get project details
  • PUT /api/project/:id - Update project
  • DELETE /api/project/:id - Delete project

See Swagger documentation for complete API reference

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ‘¨β€πŸ’» Author

Raj Koli

πŸ™ Acknowledgments

  • Express.js team for the excellent framework
  • MongoDB team for the database
  • All open-source contributors

πŸ“ž Support

For support, email support@freelancerflow.com or open an issue on GitHub.


Made with ❀️ for freelancers worldwide