add brain
This commit is contained in:
74
.brain/03. Design/01. HighLevelDesign/System_Design.md
Normal file
74
.brain/03. Design/01. HighLevelDesign/System_Design.md
Normal file
@@ -0,0 +1,74 @@
|
||||
# High-Level Design (HLD)
|
||||
|
||||
## 1. Architectural Overview
|
||||
|
||||
The system follows **Clean Architecture** principles to ensure separation of concerns, testability, and independence from frameworks. It utilizes **CQRS** (Command Query Responsibility Segregation) via the **MediatR** library to decouple read and write operations, ensuring scalable and maintainable code.
|
||||
|
||||
### 1.1. Project Layers
|
||||
|
||||
* **Domain**: Contains core business logic, entities, value objects, domain events, and custom exceptions. It has zero dependencies on other layers or external frameworks.
|
||||
* **Application**: Defines use cases and coordinates business logic. It contains MediatR Commands, Queries, Handlers, and validation rules (FluentValidation).
|
||||
* **Infrastructure**: Implements interfaces defined in the Application layer, such as Persistence (EF Core), Identity (JWT), Caching (Redis), and third-party API integrations.
|
||||
* **Presentation (WebAPI / AdminAPI)**: Acts as the entry point for clients, handling HTTP requests, routing, security middlewares, and returning standardized API responses.
|
||||
|
||||
## 2. Technology Stack & Infrastructure
|
||||
|
||||
* **Framework**: .NET Core (8/9).
|
||||
* **Persistence**: Entity Framework (EF) Core with SQL Server / PostgreSQL.
|
||||
* **Caching**: **Redis** for distributed session management, refresh token storage, and performance optimization of frequent queries.
|
||||
* **Messaging**: MediatR for in-process messaging. Extensible to asynchronous message brokers (RabbitMQ/Kafka) for background tasks and microservice communication.
|
||||
* **Observability**: **Serilog** for structured logging (sinking to Seq/Elasticsearch) and **OpenTelemetry** for distributed tracing and monitoring.
|
||||
|
||||
## 3. Core Technical Strategies
|
||||
|
||||
### 3.1. Security & Authentication Architecture
|
||||
|
||||
* **Authentication**: Stateless authentication using **JWT** (JSON Web Tokens).
|
||||
* **Token Rotation**: Implements a secure **Refresh Token** mechanism. Refresh tokens are hashed using a token hasher before being stored in the database to prevent leakage.
|
||||
* **Single Active Session**: Logging in automatically revokes previous active refresh tokens for the user, forcing a single active session.
|
||||
* **Authorization**: Role-based access control (RBAC) and policy-based authorization managed through claims-based identity.
|
||||
|
||||
### 3.2. Data Management & CQRS
|
||||
|
||||
* **Commands**: Handled by MediatR to perform write operations (Create, Update, Delete) and mutate system state. Often wrapped in database transactions via an `IUnitOfWork`.
|
||||
* **Queries**: Optimized for read-only operations, often bypassing complex domain models to query the database directly (e.g., using EF Core `AsNoTracking` or Dapper) and returning flat **DTOs** (Data Transfer Objects).
|
||||
* **Validation**: Automated input validation using **FluentValidation** integrated directly into the MediatR pipeline behavior, ensuring invalid requests are rejected before reaching handlers.
|
||||
|
||||
### 3.3. Caching Strategy (Redis)
|
||||
|
||||
* **Key Convention**: Strictly namespaced keys using the pattern `{app}:{layer}:{entity}:{action}:{identifier}`.
|
||||
* **Data Types**: Optimized use of `Hash` for objects, `String` for simple data, and `Set` for tracking grouping tags.
|
||||
* **Invalidation**: Tag-based invalidation ensures that when an entity is updated, all related cached queries are instantly purged.
|
||||
* **Mandatory TTL**: Every cached item has an explicit Time-To-Live (TTL) to prevent memory leaks and ensure data freshness.
|
||||
|
||||
### 3.4. Error Handling & Response Standard
|
||||
|
||||
* **Global Exception Handling**: Centralized middleware/exception filter to catch all unhandled exceptions, preventing stack trace leaks and transforming them into a standard JSON format.
|
||||
* **Result Pattern**: All API responses wrap data in a standardized `ApiResponse<T>` or `Result<T>` object, ensuring consistency in error codes, success markers, and payload structure across the FE/BE bridge.
|
||||
|
||||
## 4. Deployment & CI/CD Strategy
|
||||
|
||||
* **Containerization**: Multi-stage **Docker** builds for Backend APIs to ensure minimal image sizes and consistent runtime environments.
|
||||
* **Orchestration**: **Docker Compose** for local development and local testing. Target environments use Kubernetes or managed container services.
|
||||
* **CI/CD Pipelines**: Automated GitHub Actions / GitLab CI pipelines for restoring over NuGet, building, running unit and integration tests, building Docker images, and deploying to servers.
|
||||
|
||||
---
|
||||
|
||||
## 5. System Flow Diagram (Context & Container)
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
Client[Client Apps : Web / Mobile] -->|HTTPS / JWT| API[Presentation : WebAPI / AdminAPI]
|
||||
|
||||
subgraph "Clean Architecture Core"
|
||||
API -->|MediatR Command/Query| App[Application Layer]
|
||||
App -->|Uses Entities & Interfaces| Domain[Domain Layer]
|
||||
end
|
||||
|
||||
subgraph "Infrastructure Layer"
|
||||
App -->|Calls Implementations| Infra[Infrastructure Layer]
|
||||
Infra -->|EF Core Queries| DB[(SQL Database)]
|
||||
Infra -->|StackExchange.Redis| Redis[(Redis Cache)]
|
||||
Infra -->|Serilog| Logs[Logging System]
|
||||
end
|
||||
```
|
||||
86
.brain/03. Design/02. LowLevelDesign/Auth_Token_Flow.md
Normal file
86
.brain/03. Design/02. LowLevelDesign/Auth_Token_Flow.md
Normal file
@@ -0,0 +1,86 @@
|
||||
# Authentication & Token Flow (iYHCT360)
|
||||
|
||||
This document describes in detail the Authentication and Token (Access Token / Refresh Token) processing flow based on the project's actual source code. This is the core security framework designed to be reusable (base) across other projects.
|
||||
|
||||
---
|
||||
|
||||
## 1. Technology Overview & Design Patterns
|
||||
|
||||
- **JWT (JSON Web Token)**: Short-lived Access Token containing the user's basic Claims.
|
||||
- **Refresh Token Storage**: Securely stored in the Database (saving only hashed strings to prevent database leak vulnerabilities).
|
||||
- **Refresh Token Rotation**: Upon performing a token refresh, the old Refresh Token is revoked, and a completely new Refresh Token is issued (minimizing the risk of theft).
|
||||
- **Single Active Session**: Each login will revoke all currently Active Refresh Tokens of that User to ensure there is only 1 active session at a time.
|
||||
|
||||
### 1.1. JWT Configuration (`appsettings.json`)
|
||||
|
||||
System default lifecycles:
|
||||
|
||||
- **Access Token**: Lives for 15 minutes.
|
||||
- **Refresh Token**: Lives for 7 days.
|
||||
|
||||
---
|
||||
|
||||
## 2. Detailed Processing Flows
|
||||
|
||||
### 2.1. Login Flow
|
||||
|
||||
**Endpoint**: `POST /api/auth/login`
|
||||
|
||||
**Processing Steps**:
|
||||
|
||||
1. Client sends a `LoginRequest` containing: `Email` and `Password`.
|
||||
2. The system searches for the User by Email (only `IsActive` users).
|
||||
3. Verifies the password (hashing verification via `IPasswordHasher`).
|
||||
4. The system retrieves the User's corresponding Roles from the database.
|
||||
5. Generates an **Access Token** containing information (`id`, `roles`, etc.).
|
||||
6. Generates a random **Refresh Token** string.
|
||||
7. Ensures Single Active Session: The system queries the db to find and mark all previous active Refresh Tokens of the user (`RevokedAt = null` and not Expired) as revoked (`RevokedAt = DateTimeOffset.UtcNow`).
|
||||
8. **Hashing the token**: The random Refresh Token string (which is sent to the client only once) is hashed using an algorithm (e.g., `TokenHasher.ComputeHash()`) and ONLY this hash value is saved in the Database along with the IP + UserAgent.
|
||||
9. Updates the user's `LastLoginAt` and returns the information (Access Token, Refresh Token, Roles, UserType) to the Client.
|
||||
|
||||
### 2.2. Token Refresh Flow (Token Rotation)
|
||||
|
||||
**Endpoint**: `POST /api/auth/refresh-token`
|
||||
|
||||
**Processing Steps**:
|
||||
|
||||
1. Client sends both the `AccessToken` (which might be expired) and the `RefreshToken`.
|
||||
2. The system looks up the Refresh Token in the Database (stored as the hash of the original Refresh Token string) => Verifies existence, check it's not revoked (`RevokedAt == null`), and check it's not expired.
|
||||
3. Decodes the `AccessToken` using the Extract Claims function to get the `userId`. The `userId` retrieved from the token MUST match the `UserId` owning the Refresh Token.
|
||||
4. Checks if the User is still `IsActive`.
|
||||
5. Reloads the user's roles from the Database (if roles have changed while the old token was still valid, the refresh action will incorporate the new `roles` into the next Access Token).
|
||||
6. Issues a new `AccessToken` and a completely new `RefreshToken`.
|
||||
7. Manually marks the current Refresh Token as revoked (`RevokedAt = DateTimeOffset.UtcNow`).
|
||||
8. Saves the hash value of the **new RefreshToken** into the DB with a 7-day expiration.
|
||||
9. Returns the data to the Client.
|
||||
|
||||
### 2.3. Logout Flow
|
||||
|
||||
**Endpoint**: `POST /api/auth/logout`
|
||||
|
||||
**Processing Steps**:
|
||||
|
||||
1. Client sends the `RefreshToken` to the system.
|
||||
2. The system hashes the incoming token and finds the corresponding record in the DB.
|
||||
3. Marks that Token as revoked (`RevokedAt = DateTimeOffset.UtcNow`).
|
||||
4. (Optional: The Client deletes the AccessToken/RefreshToken stored locally on its device).
|
||||
|
||||
### 2.4. Password Reset (Forgot password & Reset)
|
||||
|
||||
1. **Forgot Password (`POST /api/auth/forgot-password`)**:
|
||||
- Generates a Raw Token (a `Guid.NewGuid()` string).
|
||||
- Hashes that Raw Token and saves it into the User's `SecurityStamp` field.
|
||||
- Concatenates `${user.Id}:{rawToken}`, then applies `Base64 Encode` and returns it (or sends it via Email) to act as the ResetToken.
|
||||
2. **Reset Password (`POST /api/auth/reset-password`)**:
|
||||
- `Base64` decodes the token above to extract the `userId` and `rawToken`.
|
||||
- Finds the User in the db, compares the hash of `rawToken` with the `SecurityStamp`.
|
||||
- If valid, Hashes the `NewPassword` into the DB. Sets `SecurityStamp = null` (can only be used to change the password once).
|
||||
- **Security**: Immediately revokes all active Refresh Tokens for this User to forcefully log them out across all devices.
|
||||
|
||||
---
|
||||
|
||||
## 3. Best Practices Summary Applied in the Backend
|
||||
|
||||
- Fully leverage the `TokenHasher` concept: Never store Refresh Tokens, OTP tokens, or Forgot password tokens in direct raw text. If the Database leaks, attackers still cannot use those tokens (similar to hashed passwords).
|
||||
- Always cross-check: Ensure the Refresh Token genuinely belongs to the `userId` present in the Access Token to prevent cross-token forgery.
|
||||
- Synchronization: When an Admin changes a User's Password/Roles or a User changes their own password (Reset/Change) -> The system must automatically revoke all Refresh Tokens to force a fresh log-in.
|
||||
Reference in New Issue
Block a user