{"id":29133099,"url":"https://github.com/collatzconjecture/nestjs-clean-architecture","last_synced_at":"2026-04-13T03:04:08.590Z","repository":{"id":300379513,"uuid":"1000905149","full_name":"CollatzConjecture/nestjs-clean-architecture","owner":"CollatzConjecture","description":"A modular NestJS boilerplate with CQRS, Event Sourcing, DDD, and Clean Architecture. Built-in observability with Prometheus \u0026 Grafana, API docs via Swagger, and Dockerized deployment. Ideal for scalable, maintainable applications.","archived":false,"fork":false,"pushed_at":"2025-06-21T10:38:19.000Z","size":112,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-06-21T11:28:34.942Z","etag":null,"topics":["boilerplate","boilerplate-template","docker","docker-compose","event-driven-architecture","grafana","mongodb","nestjs","prometheus","swagger","typescript"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"unlicense","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/CollatzConjecture.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-06-12T13:55:52.000Z","updated_at":"2025-06-21T10:38:22.000Z","dependencies_parsed_at":"2025-06-21T11:38:49.093Z","dependency_job_id":null,"html_url":"https://github.com/CollatzConjecture/nestjs-clean-architecture","commit_stats":null,"previous_names":["collatzconjecture/nestjs-clean-architecture"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/CollatzConjecture/nestjs-clean-architecture","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CollatzConjecture%2Fnestjs-clean-architecture","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CollatzConjecture%2Fnestjs-clean-architecture/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CollatzConjecture%2Fnestjs-clean-architecture/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CollatzConjecture%2Fnestjs-clean-architecture/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/CollatzConjecture","download_url":"https://codeload.github.com/CollatzConjecture/nestjs-clean-architecture/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/CollatzConjecture%2Fnestjs-clean-architecture/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":262727708,"owners_count":23354665,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["boilerplate","boilerplate-template","docker","docker-compose","event-driven-architecture","grafana","mongodb","nestjs","prometheus","swagger","typescript"],"created_at":"2025-06-30T07:01:59.050Z","updated_at":"2026-04-13T03:04:08.583Z","avatar_url":"https://github.com/CollatzConjecture.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# NestJS Clean Architecture with DDD, CQRS \u0026 Event Sourcing\n\nThis is an advanced boilerplate project implementing **Domain-Driven Design (DDD)**, **Clean Architecture**, **CQRS (Command Query Responsibility Segregation)**, **Event Sourcing** and MongoDB with NestJS. It provides a robust foundation for building scalable and maintainable enterprise-level applications with **proper separation of concerns** and **clean dependency direction**.\n\nIf you want more documentation about NestJS, click here [Nest](https://github.com/nestjs/nest)\n\n\u003e **📝 Note:** This version uses **MongoDB** with **Mongoose**. If you prefer the **PostgreSQL** version with **TypeORM**, you can find it at the original repository: [https://github.com/CollatzConjecture/nestjs-clean-architecture-postgres](https://github.com/CollatzConjecture/nestjs-clean-architecture-postgres)\n\n[A quick introduction to clean architecture](https://www.freecodecamp.org/news/a-quick-introduction-to-clean-architecture-990c014448d2/)\n\n![Clean Architecture](https://cdn-media-1.freecodecamp.org/images/oVVbTLR5gXHgP8Ehlz1qzRm5LLjX9kv2Zri6)\n\n## 🚀 Features\n\n### Core Architecture\n\n- **Clean Architecture**: Enforces strict separation of concerns with proper dependency direction (Infrastructure → Application → Domain).\n- **Domain-Driven Design (DDD)**: Pure business logic encapsulated in Domain Services, accessed through Repository Interfaces.\n- **CQRS**: Segregates read (Queries) and write (Commands) operations for optimized performance and scalability.\n- **Event Sourcing**: Uses an event-driven approach with sagas for orchestrating complex business processes.\n- **Repository Pattern**: Clean interfaces defined in Domain layer, implemented in Infrastructure layer.\n- **Dependency Inversion**: Domain layer depends only on abstractions, never on concrete implementations.\n\n### Proper Layer Separation\n\n- **Domain Layer**: Pure business logic, domain entities without framework dependencies, repository interfaces\n- **Application Layer**: Business orchestration, application services, CQRS coordination, framework-agnostic services\n- **API Layer**: HTTP controllers, DTOs, request/response handling, framework-specific HTTP concerns\n- **Infrastructure Layer**: Database implementations, external API calls, concrete repository classes, global services\n\n### Security \u0026 Authentication\n\n- **JWT Authentication**: Implements secure, token-based authentication with refresh token rotation.\n- **Google OAuth2 Integration**: Secure third-party authentication with Google accounts, including CSRF protection.\n- **Role-Based Access Control (RBAC)**: Complete implementation with protected routes and role-based guards.\n- **Secure Password Storage**: Hashes passwords using `bcrypt` with salt rounds.\n- **Sensitive Data Encryption**: Encrypts sensitive fields (e.g., user emails) at rest in the database using AES-256-CBC.\n- **Blind Indexing**: Allows for securely querying encrypted data without decrypting it first.\n- **CSRF Protection**: OAuth flows protected against Cross-Site Request Forgery attacks using state parameters.\n\n### Infrastructure \u0026 Operations\n\n- **MongoDB Integration**: Utilizes Mongoose for structured data modeling with a NoSQL database.\n- **Containerized Environment**: Full Docker and Docker Compose setup for development and production.\n- **Health Checks**: Provides application health monitoring endpoints via Terminus.\n- **Structured Logging**: Advanced logging system with business-context awareness and dependency injection.\n- **Application Metrics**: Exposes performance metrics for Prometheus.\n- **Data Visualization**: Comes with a pre-configured Grafana dashboard for visualizing metrics.\n- **Request Throttling**: Built-in rate limiting to prevent abuse and ensure API stability.\n\n### Testing\n\n- **Unit \u0026 Integration Tests**: A suite of tests for domain, application, and infrastructure layers.\n- **E2E Tests**: End-to-end tests to ensure API functionality from request to response.\n- **High Test Coverage**: Configured to report and maintain high code coverage.\n- **Mocking**: Clear patterns for mocking database and service dependencies.\n\n## Getting Started\n\n```bash\ngit clone https://github.com/CollatzConjecture/nestjs-clean-architecture\ncd nestjs-clean-architecture\n```\n\n### 📁 Project Structure\n\n```\n.\n├── doc/\n│   ├── common.http              # Common API requests\n│   └── users.http               # User-specific API requests\n├── src/\n│   ├── api/                     # API Layer (HTTP Controllers \u0026 DTOs)\n│   │   ├── controllers/\n│   │   │   └── *.controller.ts  # HTTP endpoints (auth, profile, hello)\n│   │   ├── dto/\n│   │   │   ├── auth/            # Authentication DTOs\n│   │   │   │   └── *.dto.ts     # Login \u0026 register DTOs\n│   │   │   └── *.dto.ts         # Profile management DTOs\n│   │   └── api.module.ts        # API module configuration\n│   ├── application/             # Application Layer (Business Orchestration)\n│   │   ├── __test__/\n│   │   │   └── *.spec.ts        # Application layer tests\n│   │   ├── auth/\n│   │   │   ├── command/         # Auth commands \u0026 handlers\n│   │   │   │   ├── *.command.ts # Create/delete auth user commands\n│   │   │   │   └── handler/\n│   │   │   │       └── *.handler.ts # Command handlers\n│   │   │   ├── events/          # Auth domain events\n│   │   │   │   └── *.event.ts   # User created/deleted events\n│   │   │   ├── sagas/\n│   │   │   │   └── *.saga.ts    # Registration flow orchestration\n│   │   │   ├── decorators/\n│   │   │   │   └── *.decorator.ts # Custom decorators (roles)\n│   │   │   ├── guards/\n│   │   │   │   └── *.guard.ts   # Authentication \u0026 authorization guards\n│   │   │   ├── *.strategy.ts    # Auth strategies (JWT, local, Google OAuth)\n│   │   │   └── auth.module.ts   # Auth module configuration\n│   │   ├── decorators/\n│   │   │   └── *.decorator.ts   # Global decorators (current user)\n│   │   ├── interfaces/\n│   │   │   └── *.interface.ts   # Application interfaces\n│   │   ├── interceptors/\n│   │   │   └── *.interceptor.ts # Request logging interceptors\n│   │   ├── middlewere/\n│   │   │   └── *.middleware.ts  # HTTP middleware (logging)\n│   │   ├── services/\n│   │   │   └── *.service.ts     # Application services (auth, profile, logger)\n│   │   ├── profile/\n│   │   │   ├── command/         # Profile commands \u0026 handlers\n│   │   │   │   ├── *.command.ts # Profile commands\n│   │   │   │   └── handler/\n│   │   │   │       └── *.handler.ts # Command handlers\n│   │   │   ├── events/          # Profile domain events\n│   │   │   │   └── *.event.ts   # Profile events\n│   │   │   └── profile.module.ts # Profile module configuration\n│   │   └── application.module.ts # Application module aggregator\n│   ├── domain/                  # Domain Layer (Pure Business Logic)\n│   │   ├── __test__/\n│   │   │   └── *.spec.ts        # Domain layer tests\n│   │   ├── aggregates/          # Domain aggregates\n│   │   ├── entities/\n│   │   │   ├── *.ts             # Pure domain entities (Auth, Profile)\n│   │   │   └── enums/           # Domain enums\n│   │   │       └── *.enum.ts    # Role enums, etc.\n│   │   ├── interfaces/\n│   │   │   └── repositories/    # Repository contracts defined by domain\n│   │   │       └── *.interface.ts # Repository interfaces\n│   │   └── services/\n│   │       └── *.service.ts     # Pure business logic services\n│   ├── infrastructure/          # Infrastructure Layer (External Concerns)\n│   │   ├── database/\n│   │   │   ├── database.module.ts    # Database configuration\n│   │   │   └── database.providers.ts # Database providers\n│   │   ├── health/\n│   │   │   └── *.check.ts       # Health check configurations\n│   │   ├── logger/\n│   │   │   └── logger.module.ts # Global logger module\n│   │   ├── models/\n│   │   │   ├── *.model.ts       # MongoDB models (auth, profile)\n│   │   │   └── index.ts         # Model exports\n│   │   └── repository/\n│   │       └── *.repository.ts  # Repository implementations\n│   ├── main.ts                  # Application entry point\n│   ├── app.module.ts           # Root application module\n│   └── constants.ts            # Application constants\n├── test/\n│   ├── *.e2e-spec.ts           # End-to-end tests\n│   ├── jest-e2e.json           # E2E test configuration\n│   └── setup-e2e.ts            # E2E test setup\n├── prometheus/\n│   └── prometheus.yml          # Prometheus configuration\n├── docker-compose*.yml         # Docker Compose configurations (dev, prod)\n└── Dockerfile                  # Container definition\n```\n\n## 🏗️ Architecture Overview\n\n### Layer Architecture\n\nThis project follows a strict 4-layer architecture:\n\n1. **API Layer** (`src/api/`): HTTP controllers, DTOs, and request/response handling\n2. **Application Layer** (`src/application/`): Business orchestration, CQRS coordination, and application services\n3. **Domain Layer** (`src/domain/`): Pure business logic, entities, and domain services\n4. **Infrastructure Layer** (`src/infrastructure/`): Database, external services, and technical implementations\n\n### Module Structure\n\n- **ApiModule**: Aggregates all HTTP controllers and imports ApplicationModule\n- **ApplicationModule**: Central orchestrator that imports and exports feature modules\n- **AuthModule**: Self-contained authentication feature with all its dependencies\n- **ProfileModule**: Self-contained profile management feature with all its dependencies\n- **LoggerModule**: Global infrastructure service for application-wide logging\n\n### CQRS Implementation\n\n- **Commands**: Handle write operations (Create, Update, Delete). Located in `src/application/*/command`.\n- **Queries**: Handle read operations (Find, Get). Located in `src/application/*/query`.\n- **Handlers**: Process commands and queries separately with proper business-context logging.\n- **Events**: Publish domain events for side effects and inter-module communication.\n\n### Event-Driven Flow\n\n1. **User Registration**:\n\n   ```\n   API Controller → Application Service → Domain Service (validation) →\n   RegisterCommand → CreateAuthUser → AuthUserCreated Event →\n   RegistrationSaga → CreateProfile → ProfileCreated\n   ```\n\n2. **Authentication**:\n\n   ```\n   API Controller → Application Service → Domain Service (email validation) →\n   LoginCommand → ValidateUser → JWT Token Generation\n   ```\n\n3. **Google OAuth Flow**:\n\n   ```\n   /auth/google → Google OAuth → /auth/google/redirect →\n   Domain Service (validation) → FindOrCreateUser → JWT Token Generation\n   ```\n\n4. **Error Handling**:\n   ```\n   ProfileCreationFailed Event → RegistrationSaga →\n   DeleteAuthUser (Compensating Transaction)\n   ```\n\n### Dependency Injection \u0026 Module Boundaries\n\n- **Feature Modules**: Each feature (Auth, Profile) manages its own dependencies\n- **Domain Services**: Injected via factories to maintain Clean Architecture principles\n- **Repository Pattern**: Interfaces defined in domain, implementations in infrastructure\n- **Global Services**: Logger provided globally via `@Global()` decorator\n\n## 📋 Prerequisites\n\n- Node.js 20+\n- Docker and Docker Compose\n- MongoDB (included in Docker Compose)\n- Google OAuth2 credentials (for Google login functionality)\n\n## 🐳 Running with Docker Compose\n\nThe project is configured to run seamlessly with Docker. Use the pnpm scripts from `package.json` for convenience.\n\n```bash\n# Build and start containers in detached mode for development\n$ pnpm run docker:dev\n\n# Build and start containers for production\n$ pnpm run docker:prod\n\n# View logs for the API service\n$ pnpm run docker:logs\n\n# Stop all running containers\n$ pnpm run docker:down\n\n# Restart the development environment\n$ pnpm run docker:restart\n```\n\n### 🌐 Service Access\n\n- **Application**: http://localhost:4000\n- **API Documentation (Swagger)**: http://localhost:4000/api\n- **MongoDB**: localhost:27017\n- **Prometheus**: http://localhost:9090\n- **Grafana**: http://localhost:3000 (admin/admin)\n\n## 📦 Installation\n\n```bash\n$ pnpm install\n```\n\n## 🚀 Running the Application\n\n```bash\n# Development\n$ pnpm run start\n\n# Watch mode (recommended for development)\n$ pnpm run start:dev\n\n# Production mode\n$ pnpm run start:prod\n\n# Debug mode\n$ pnpm run start:debug\n```\n\n## 🧪 Testing\n\n```bash\n# Unit tests\n$ pnpm run test\n\n# E2E tests\n$ pnpm run test:e2e\n\n# Test coverage\n$ pnpm run test:cov\n\n# Watch mode\n$ pnpm run test:watch\n```\n\n## 🧹 Linting\n\n```bash\n# Check code style\n$ pnpm run lint\n\n# Auto-fix issues where possible\n$ pnpm run lint:fix\n```\n\n## 🧪 API Testing\n\nYou can import this [Postman collection](./NestJS%20CA-DDD.postman_collection.json) to test the API endpoints.\n\nThe collection includes:\n\n- **Authentication endpoints**: Register, login, logout, Google OAuth\n- **Profile management**: Create, read, update profile data\n- **Protected routes**: Examples with JWT token authentication\n- **Admin endpoints**: Role-based access control examples\n- **Environment variables**: Pre-configured for localhost development\n\n### Using the Postman Collection\n\n1. **Import the collection**: Download and import `NestJS CA-DDD.postman_collection.json` into Postman\n2. **Set environment variables**: Configure the following variables in Postman:\n   - `localhost`: `http://localhost` (or your host)\n   - `port`: `4000` (or your configured port)\n   - `Authorization`: `Bearer \u003cyour-jwt-token\u003e` (set after login)\n3. **Test the flow**:\n   - Start with user registration\n   - Login to get JWT token\n   - Use the token for protected endpoints\n\n## 🔐 API Endpoints\n\n### Authentication\n\n```http\nPOST /auth/register       # User registration\nPOST /auth/login          # User login\nPOST /auth/logout         # User logout (Protected)\nPOST /auth/refresh-token  # Token refresh (Protected)\nGET  /auth/google         # Initiate Google OAuth login\nGET  /auth/google/redirect # Google OAuth callback\nGET  /auth/:id            # Get user by auth ID (Protected)\nDELETE /auth/:id          # Delete user by auth ID (Protected)\n```\n\n### Profile Management (Protected)\n\n```http\nGET  /profile/all         # Get all user profiles (Admin only)\nGET  /profile/admins      # Get all admin users (Admin only)\nGET  /profile/:id         # Get user profile by ID\nPOST /profile             # Create a new profile\n```\n\n### Health \u0026 Monitoring\n\n```http\nGET  /hello               # Health check endpoint\nGET  /health              # Detailed health check\nGET  /metrics             # Prometheus metrics\n```\n\n### Example Usage\n\n#### Traditional Registration \u0026 Login\n\n```bash\n# Register a new user\ncurl -X POST http://localhost:4000/auth/register \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"name\": \"John\",\n    \"lastname\": \"Doe\",\n    \"age\": 30,\n    \"email\": \"john@example.com\",\n    \"password\": \"securePassword123\"\n  }'\n\n# Login\ncurl -X POST http://localhost:4000/auth/login \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\n    \"email\": \"john@example.com\",\n    \"password\": \"securePassword123\"\n  }'\n```\n\n#### Google OAuth Login\n\n```bash\n# Initiate Google login (redirects to Google)\ncurl -X GET http://localhost:4000/auth/google\n\n# The callback is handled automatically after Google authentication\n# Returns JWT token upon successful authentication\n```\n\n#### Protected Routes\n\n```bash\n# Access protected route\ncurl -X GET http://localhost:4000/profile/123 \\\n  -H \"Authorization: Bearer YOUR_JWT_TOKEN\"\n\n# Admin-only route\ncurl -X GET http://localhost:4000/profile/all \\\n  -H \"Authorization: Bearer YOUR_ADMIN_JWT_TOKEN\"\n```\n\n## 🛠️ Built With\n\n### Core Framework\n\n- **[NestJS](https://nestjs.com/)** - Progressive Node.js framework\n- **[TypeScript](https://www.typescriptlang.org/)** - Type-safe JavaScript\n\n### Architecture \u0026 Patterns\n\n- **[@nestjs/cqrs](https://docs.nestjs.com/recipes/cqrs)** - CQRS implementation\n- **[@nestjs/event-emitter](https://docs.nestjs.com/techniques/events)** - Event handling\n\n### Authentication \u0026 Security\n\n- **[@nestjs/jwt](https://docs.nestjs.com/security/authentication)** - JWT implementation\n- **[@nestjs/passport](https://docs.nestjs.com/security/authentication)** - Authentication strategies\n- **[@nestjs/throttler](https://docs.nestjs.com/security/rate-limiting)** - Rate limiting\n- **[bcrypt](https://www.npmjs.com/package/bcrypt)** - Password hashing\n- **[cookie-parser](https://www.npmjs.com/package/cookie-parser)** - Cookie handling for OAuth state\n\n### Database \u0026 Storage\n\n- **[Mongoose](https://mongoosejs.com/)** - MongoDB object modeling\n- **[MongoDB](https://www.mongodb.com/)** - Document database\n\n### Monitoring \u0026 Health\n\n- **[@nestjs/terminus](https://docs.nestjs.com/recipes/terminus)** - Health checks\n- **[Prometheus](https://prometheus.io/)** - Metrics collection\n- **[Grafana](https://grafana.com/)** - Metrics visualization\n\n### Testing\n\n- **[Jest](https://jestjs.io/)** - Testing framework\n- **[Supertest](https://www.npmjs.com/package/supertest)** - HTTP assertion library\n\n### Development Tools\n\n- **[Nodemon](https://nodemon.io/)** - Development server\n- **[Docker](https://www.docker.com/)** - Containerization\n\n## 🏛️ Domain-Driven Design\n\n### Bounded Contexts\n\n- **Authentication Context**: User login, registration, tokens, OAuth integration\n- **Profile Context**: User profile management, personal data\n\n### Aggregates\n\n- **UserAggregate**: Manages user lifecycle and events across auth and profile contexts\n\n### Domain Events\n\n- `AuthUserCreatedEvent`: Triggered after successful user creation\n- `AuthUserDeletedEvent`: Triggered when user is deleted (compensating action)\n- `ProfileCreationFailedEvent`: Triggered when profile creation fails\n\n### Sagas\n\n- **RegistrationSaga**: Orchestrates user registration process\n  - Handles profile creation after auth user creation\n  - Implements compensating transactions for failures\n  - Supports both traditional and OAuth registration flows\n\n## 📈 Monitoring \u0026 Observability\n\n### Structured Logging\n\n- **Business-Context Logging**: Logs focus on business events rather than technical execution\n- **Dependency Injection**: Logger service is injected throughout the application\n- **Consistent Format**: All logs include module, method, and timestamp information\n- **Security Audit Trail**: Comprehensive logging of authentication attempts and outcomes\n\n### Health Checks\n\n- Database connectivity\n- Memory usage\n- Disk space\n\n### Metrics (Prometheus)\n\n- HTTP request duration\n- Request count by endpoint\n- Error rates\n- Database connection pool\n- Authentication success/failure rates\n\n### Dashboards (Grafana)\n\n- Application performance metrics\n- Database statistics\n- Error tracking\n- Response time analysis\n- Authentication analytics\n\n## ⚙️ Configuration\n\n1.  **Clone the repository:**\n\n    ```bash\n    git clone https://github.com/CollatzConjecture/nestjs-clean-architecture\n    cd nestjs-clean-architecture\n    ```\n\n2.  **Create an environment file:**\n\n    Create a file named `.env` in the root of the project by copying the example file.\n\n    ```bash\n    cp .env.example .env\n    ```\n\n3.  **Generate Secrets:**\n\n    Your `.env` file requires several secret keys to run securely. Use the following command to generate a cryptographically strong secret:\n\n    ```bash\n    node -e \"console.log(require('crypto').randomBytes(32).toString('hex'))\"\n    ```\n\n    Run this command for each of the following variables in your `.env` file and paste the result:\n\n    - `JWT_SECRET`\n    - `JWT_REFRESH_SECRET`\n    - `EMAIL_ENCRYPTION_KEY`\n    - `EMAIL_BLIND_INDEX_SECRET`\n\n    **Do not use the same value for different keys.**\n\n4.  **Configure Google OAuth2 (Optional):**\n\n    To enable Google login functionality, you'll need to:\n\n    a. Go to the [Google Cloud Console](https://console.cloud.google.com/)\n\n    b. Create a new project or select an existing one\n\n    c. Enable the Google+ API\n\n    d. Create OAuth 2.0 credentials (Web application type)\n\n    e. Add your redirect URI: `http://localhost:4000/auth/google/redirect`\n\n    f. Add the following to your `.env` file:\n\n    ```env\n    GOOGLE_CLIENT_ID=your_google_client_id_here\n    GOOGLE_CLIENT_SECRET=your_google_client_secret_here\n    GOOGLE_CALLBACK_URL=http://localhost:4000/auth/google/redirect\n    ```\n\n## 🔒 Security Features\n\n### Authentication Security\n\n- **JWT with Refresh Tokens**: Secure token-based authentication with automatic refresh\n- **Password Security**: Bcrypt hashing with configurable salt rounds\n- **OAuth2 Security**: CSRF protection using state parameters in OAuth flows\n- **Rate Limiting**: Configurable throttling on sensitive endpoints\n\n### Data Protection\n\n- **Encryption at Rest**: Sensitive data encrypted using AES-256-CBC\n- **Blind Indexing**: Secure querying of encrypted data\n- **Input Validation**: Comprehensive DTO validation using class-validator\n- **SQL Injection Prevention**: MongoDB with Mongoose provides built-in protection\n- **Automatic Timestamps**: All models include `createdAt` and `updatedAt` for audit trails\n\n### Access Control\n\n- **Role-Based Authorization**: Complete RBAC implementation with guards\n- **Route Protection**: JWT guards on sensitive endpoints\n- **Admin Controls**: Separate endpoints for administrative functions\n\n## 👨‍💻 Authors\n\n- **Jerry Lucas** - _Current Maintainer_ - [GitHub](https://github.com/CollatzConjecture)\n\n## 📄 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## 🙏 Acknowledgments\n\n- **Edwin Caminero** - Inspiration for this project\n- Clean Architecture principles by Robert C. Martin\n- Domain-Driven Design concepts by Eric Evans\n- CQRS and Event Sourcing patterns\n- NestJS framework and community\n\n## 📚 Further Reading\n\n- [Clean Architecture](https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html)\n- [Domain-Driven Design](https://martinfowler.com/bliki/DomainDrivenDesign.html)\n- [CQRS Pattern](https://martinfowler.com/bliki/CQRS.html)\n- [Event Sourcing](https://martinfowler.com/eaaDev/EventSourcing.html)\n- [NestJS Documentation](https://docs.nestjs.com/)\n- [OAuth 2.0 Security Best Practices](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-security-topics)\n- [Repository Pattern](https://martinfowler.com/eaaCatalog/repository.html)\n- [Dependency Inversion Principle](https://blog.cleancoder.com/uncle-bob/2016/01/04/ALittleArchitecture.html)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcollatzconjecture%2Fnestjs-clean-architecture","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcollatzconjecture%2Fnestjs-clean-architecture","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcollatzconjecture%2Fnestjs-clean-architecture/lists"}