Enhance web-admin application with internationalization and UI improvements

- Integrated `@hookform/resolvers` and `@radix-ui/react-avatar` for improved form handling and avatar components.
- Updated Tailwind CSS configuration and global styles for better responsiveness and accessibility.
- Refactored layout components to include `I18nProvider` for dynamic language support.
- Enhanced various UI elements with translated strings for better user experience.
- Improved error handling and validation messages in forms to support localization.

These changes aim to provide a more inclusive and user-friendly experience in the web-admin application.
This commit is contained in:
Ho Ngoc Hai
2026-01-02 10:36:38 +07:00
parent f43aec8a03
commit 5ce05c63e7
83 changed files with 6752 additions and 811 deletions

View File

@@ -0,0 +1,914 @@
---
name: IAM Service Audit Plan
overview: "Kế hoạch kiểm tra toàn diện cho IAM Service bao gồm: logic nghiệp vụ, quy trình build, bảo mật, và triển khai môi trường dev/staging/production. Plan được chia thành 6 phases: Pre-deployment Audit, Security Fixes, Local Environment, Staging Deployment, Production Deployment, và Post-deployment."
todos:
# Phase 1: Pre-deployment Audit - Business Logic Review
- id: audit-auth-1
content: "Review Authentication Module - Registration Flow: Check email validation, password hashing with bcrypt cost 12, user profile creation in services/iam-service/src/modules/auth/auth.service.ts"
status: pending
- id: audit-auth-2
content: "Review Authentication Module - Login Flow: Check password verification, JWT generation (access + refresh), session creation, MFA integration in services/iam-service/src/modules/auth/auth.service.ts"
status: pending
- id: audit-auth-3
content: "Review Authentication Module - Token Refresh: Check token family tracking, refresh token rotation, replay attack detection in services/iam-service/src/modules/token/jwt.service.ts"
status: pending
- id: audit-auth-4
content: "Review Authentication Module - Password Change: Check refresh token revocation, audit logging in services/iam-service/src/modules/auth/change-password.service.ts"
status: pending
- id: audit-rbac-1
content: "Review RBAC Module - Permission Resolution: Check hierarchy (Direct user → Role → Group → Policy) in services/iam-service/src/modules/rbac/rbac.service.ts"
status: pending
- id: audit-rbac-2
content: "Review RBAC Module - Role Assignment: Check expiration handling in services/iam-service/src/modules/rbac/rbac.service.ts"
status: pending
- id: audit-rbac-3
content: "Review RBAC Module - Policy Engine: Check JSON Logic implementation in services/iam-service/src/modules/rbac/policy.engine.ts"
status: pending
- id: audit-rbac-4
content: "Review RBAC Module - Permission Caching: Verify 5 min TTL and cache invalidation in services/iam-service/src/core/cache/cache.service.ts"
status: pending
- id: audit-identity-1
content: "Review Identity Module - User Management: Check CRUD operations, bulk import/export in services/iam-service/src/modules/identity/user/user.service.ts"
status: pending
- id: audit-identity-2
content: "Review Identity Module - Profile Management: Check custom fields, avatar upload/delete in services/iam-service/src/modules/identity/profile/profile.service.ts"
status: pending
- id: audit-identity-3
content: "Review Identity Module - Verification: Check email/phone/document verification flows in services/iam-service/src/modules/identity/verification/verification.service.ts"
status: pending
- id: audit-identity-4
content: "Review Identity Module - Organizations: Check multi-tenant support, hierarchical structure in services/iam-service/src/modules/identity/organization/organization.service.ts"
status: pending
- id: audit-identity-5
content: "Review Identity Module - Groups: Check member management, group-based permissions in services/iam-service/src/modules/identity/group/group.service.ts"
status: pending
- id: audit-access-1
content: "Review Access Module - Access Requests: Check workflow, approval chains, JIT access in services/iam-service/src/modules/access/request/request.service.ts"
status: pending
- id: audit-access-2
content: "Review Access Module - Access Reviews: Check certification campaigns, automated cleanup in services/iam-service/src/modules/access/review/review.service.ts"
status: pending
- id: audit-access-3
content: "Review Access Module - Access Analytics: Check usage tracking, risk identification in services/iam-service/src/modules/access/analytics/analytics.service.ts"
status: pending
- id: audit-mfa-1
content: "Review MFA Module - TOTP: Check TOTP implementation using speakeasy library in services/iam-service/src/modules/mfa/mfa.service.ts"
status: pending
- id: audit-mfa-2
content: "Review MFA Module - QR Code: Check QR code generation in services/iam-service/src/modules/mfa/mfa.service.ts"
status: pending
- id: audit-mfa-3
content: "Review MFA Module - WebAuthn: Check WebAuthn support in services/iam-service/src/modules/mfa/mfa.service.ts"
status: pending
- id: audit-mfa-4
content: "Review MFA Module - Multiple Devices: Check multiple devices per user support in services/iam-service/src/modules/mfa/mfa.service.ts"
status: pending
- id: audit-mfa-5
content: "Review MFA Module - Recovery Flow: Verify MFA recovery flow exists (NOTE: Currently missing, needs review)"
status: pending
- id: audit-social-1
content: "Review Social Authentication Module: Check Google/Facebook/GitHub OAuth flows, account linking, token refresh in services/iam-service/src/modules/social/social.service.ts"
status: pending
- id: audit-oidc-1
content: "Review OIDC Provider Module: Check discovery endpoint, authorization code flow, token exchange, JWKS endpoint in services/iam-service/src/modules/oidc/oidc-provider.service.ts"
status: pending
- id: audit-session-1
content: "Review Session Management Module: Check device fingerprinting, session expiration, revocation, activity tracking in services/iam-service/src/modules/session/session.service.ts"
status: pending
- id: audit-governance-1
content: "Review Governance Module: Check compliance reporting (GDPR, SOC2, ISO27001), policy management, risk scoring in services/iam-service/src/modules/governance/"
status: pending
- id: audit-cache-1
content: "Review Cache Service: Check multi-layer caching (L1: Memory, L2: Redis, L3: DB), cache warming, invalidation in services/iam-service/src/core/cache/cache.service.ts"
status: pending
- id: audit-events-1
content: "Review Event Sourcing: Check audit logging for all security events, 7-year retention in services/iam-service/src/core/events/"
status: pending
# Phase 1: Pre-deployment Audit - Build & Error Checking
- id: audit-build-1
content: "Run TypeScript typecheck: cd services/iam-service && pnpm typecheck - Verify no TypeScript errors"
status: pending
- id: audit-build-2
content: "Run TypeScript build: cd services/iam-service && pnpm build - Verify build succeeds, check for unused variables/imports"
status: pending
- id: audit-build-3
content: "Verify Type Safety: Check type safety for Prisma models, verify path aliases (@/*) working correctly"
status: pending
- id: audit-lint-1
content: "Run ESLint: cd services/iam-service && pnpm lint - Verify coding standards compliance"
status: pending
- id: audit-lint-2
content: "Check Code Quality: Verify no console.log in production code, proper error handling, no security anti-patterns"
status: pending
- id: audit-prisma-1
content: "Generate Prisma Client: cd services/iam-service && pnpm prisma:generate - Verify generation succeeds"
status: pending
- id: audit-prisma-2
content: "Validate Prisma Schema: Verify schema syntax valid, all relations properly defined, indexes optimized, migration files consistent"
status: pending
- id: audit-test-1
content: "Run Unit Tests: cd services/iam-service && pnpm test:unit - Verify all unit tests pass"
status: pending
- id: audit-test-2
content: "Run E2E Tests: cd services/iam-service && pnpm test:e2e - Verify all E2E tests pass"
status: pending
- id: audit-test-3
content: "Generate Test Coverage: cd services/iam-service && pnpm test:coverage - Verify coverage >= 70% (branches, functions, lines, statements)"
status: pending
- id: audit-docker-1
content: "Build Docker Image: docker build -t iam-service:test -f services/iam-service/Dockerfile . - Verify multi-stage build succeeds"
status: pending
- id: audit-docker-2
content: "Verify Docker Image: Check image size <500MB, non-root user configured, health check functional"
status: pending
# Phase 2: Security Fixes - CRITICAL
- id: security-mfa-1
content: "CRITICAL: Create Encryption Service - Create services/iam-service/src/core/security/encryption.service.ts with encrypt/decrypt functions using crypto module"
status: pending
- id: security-mfa-2
content: "CRITICAL: Update Schema for MFA Encryption - Update prisma/schema.prisma to support encrypted MFA secret fields (add encrypted field or use existing secret field with encryption layer)"
status: pending
- id: security-mfa-3
content: "CRITICAL: Update MFA Service - Update services/iam-service/src/modules/mfa/mfa.service.ts to encrypt MFA secrets before saving and decrypt when reading"
status: pending
- id: security-refresh-1
content: "CRITICAL: Hash Refresh Tokens - Update services/iam-service/src/modules/token/jwt.service.ts to hash refresh tokens (SHA-256) before storing in database"
status: pending
- id: security-refresh-2
content: "CRITICAL: Update Refresh Token Validation - Update refresh token validation logic in jwt.service.ts to compare hashes instead of plaintext tokens"
status: pending
- id: security-jwt-1
content: "CRITICAL: Block Default JWT Secrets - Update services/iam-service/src/config/jwt.config.ts to throw error if default secrets are used when NODE_ENV === 'production'"
status: pending
# Phase 2: Security Fixes - MEDIUM
- id: security-input-1
content: "MEDIUM: Install DOMPurify: cd services/iam-service && pnpm add dompurify @types/dompurify"
status: pending
- id: security-input-2
content: "MEDIUM: Update Input Sanitization - Update services/iam-service/src/utils/helpers.ts sanitizeInput function to use DOMPurify instead of simple < > removal"
status: pending
- id: security-password-1
content: "MEDIUM: Add Password Complexity Schema - Update services/iam-service/src/modules/auth/auth.dto.ts RegisterDto to enforce: uppercase, lowercase, numbers, symbols (minimum 8 characters)"
status: pending
- id: security-password-2
content: "MEDIUM: Update Change Password Schema - Update services/iam-service/src/modules/auth/auth.dto.ts ChangePasswordDto to enforce same password complexity rules"
status: pending
- id: security-fingerprint-1
content: "MEDIUM: Install FingerprintJS: cd services/iam-service && pnpm add @fingerprintjs/fingerprintjs"
status: pending
- id: security-fingerprint-2
content: "MEDIUM: Update Device Fingerprinting - Update services/iam-service/src/modules/token/cookie.service.ts to use @fingerprintjs/fingerprintjs library instead of basic User-Agent + IP hash"
status: pending
- id: security-lockout-1
content: "MEDIUM: Add Lockout Fields to Schema - Update prisma/schema.prisma User model to add failedLoginAttempts (Int, default 0) and lockedUntil (DateTime?) fields"
status: pending
- id: security-lockout-2
content: "MEDIUM: Create Account Lockout Service - Create services/iam-service/src/modules/auth/account-lockout.service.ts with lockout logic and exponential backoff"
status: pending
- id: security-lockout-3
content: "MEDIUM: Update Auth Service for Lockout - Update services/iam-service/src/modules/auth/auth.service.ts to track failed attempts and check lockout status before login"
status: pending
- id: security-lockout-4
content: "MEDIUM: Create Lockout Migration - Create Prisma migration for failedLoginAttempts and lockedUntil fields"
status: pending
# Phase 2: Security Fixes - LOW
- id: security-audit-1
content: "LOW: Run npm audit: cd services/iam-service && npm audit - Review vulnerabilities"
status: pending
- id: security-audit-2
content: "LOW: Fix npm vulnerabilities: cd services/iam-service && npm audit fix - Apply fixes for vulnerabilities"
status: pending
- id: security-cors-1
content: "LOW: Review CORS Configuration - Check services/iam-service/src/main.ts CORS settings, verify necessity of credentials enabled"
status: pending
- id: security-social-1
content: "LOW: Review Social Token Storage - Check services/iam-service/prisma/schema.prisma SocialAccount model, consider encryption for accessToken and refreshToken fields"
status: pending
- id: security-backup-1
content: "LOW: Design MFA Backup Codes - Design backup codes generation and storage strategy for MFA recovery scenarios"
status: pending
# Phase 3: Local Environment
- id: local-env-1
content: "Copy Environment File: cp deployments/local/env.local.example deployments/local/.env.local"
status: pending
- id: local-env-2
content: "Update DATABASE_URL: Set DATABASE_URL in deployments/local/.env.local to Neon PostgreSQL connection string"
status: pending
- id: local-env-3
content: "Update REDIS_URL: Set REDIS_URL in deployments/local/.env.local to redis://localhost:6379"
status: pending
- id: local-env-4
content: "Generate JWT Secrets: Generate new JWT_SECRET, JWT_REFRESH_SECRET, JWT_ID_SECRET (NOT defaults) and update deployments/local/.env.local"
status: pending
- id: local-env-5
content: "Update Social Auth Credentials: Set Google/Facebook/GitHub OAuth credentials in deployments/local/.env.local"
status: pending
- id: local-docker-1
content: "Start Docker Compose: cd deployments/local && docker-compose up -d"
status: pending
- id: local-docker-2
content: "Verify Docker Services: Check Traefik, IAM Service, Redis, PostgreSQL containers are running successfully"
status: pending
- id: local-migrate-1
content: "Run Prisma Migrate: cd services/iam-service && pnpm prisma:migrate - Verify migrations apply successfully"
status: pending
- id: local-migrate-2
content: "Run Prisma Seed: cd services/iam-service && pnpm prisma:seed - Verify seed data is created"
status: pending
- id: local-verify-1
content: "Test Traefik Dashboard: Open http://localhost:8080 and verify Traefik dashboard loads"
status: pending
- id: local-verify-2
content: "Test IAM Service: Open http://localhost:5001 and verify service is accessible"
status: pending
- id: local-verify-3
content: "Test API Gateway: Test http://localhost/api/v1/auth endpoint"
status: pending
- id: local-verify-4
content: "Test Redis: Verify Redis connection on localhost:6379"
status: pending
- id: local-health-1
content: "Test Liveness Endpoint: curl http://localhost:5001/health/live - Verify returns 200 OK"
status: pending
- id: local-health-2
content: "Test Readiness Endpoint: curl http://localhost:5001/health/ready - Verify returns 200 OK (includes DB check)"
status: pending
- id: local-health-3
content: "Test Metrics Endpoint: curl http://localhost:5001/metrics - Verify Prometheus metrics are returned"
status: pending
- id: local-test-1
content: "Test Registration Flow: Register new user via API, verify email validation, password hashing, profile creation"
status: pending
- id: local-test-2
content: "Test Login Flow: Login with registered user, verify JWT tokens, session creation"
status: pending
- id: local-test-3
content: "Test Logout Flow: Logout user, verify session revocation"
status: pending
- id: local-test-4
content: "Test Authorization: Test RBAC/ABAC permissions with different user roles"
status: pending
- id: local-test-5
content: "Test MFA: Test TOTP setup, QR code generation, WebAuthn if implemented"
status: pending
- id: local-test-6
content: "Test Social Login: Test Google/Facebook/GitHub OAuth flows"
status: pending
- id: local-test-7
content: "Review Logs and Metrics: Check application logs and Prometheus metrics for errors"
status: pending
# Phase 4: Staging Deployment
- id: staging-k8s-1
content: "Create Staging Namespace: kubectl create namespace staging"
status: pending
- id: staging-k8s-2
content: "Create Staging Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='...' --from-literal=jwt-refresh-secret='...' -n staging"
status: pending
- id: staging-k8s-3
content: "Apply Staging ConfigMap: kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml"
status: pending
- id: staging-k8s-4
content: "Deploy Staging Service: kubectl apply -f deployments/staging/kubernetes/iam-service.yaml"
status: pending
- id: staging-k8s-5
content: "Apply Staging Ingress: kubectl apply -f deployments/staging/kubernetes/ingress.yaml"
status: pending
- id: staging-migrate-1
content: "Run Staging Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy - Verify migrations apply successfully"
status: pending
- id: staging-verify-1
content: "Check Staging Pods: kubectl get pods -n staging - Verify pods are running"
status: pending
- id: staging-verify-2
content: "Check Staging Logs: kubectl logs -f deployment/iam-service -n staging - Review logs for errors"
status: pending
- id: staging-verify-3
content: "Describe Staging Pod: kubectl describe pod <pod-name> -n staging - Verify pod status and events"
status: pending
- id: staging-test-1
content: "Run Staging Smoke Tests: Execute basic API endpoint tests (health, auth endpoints)"
status: pending
- id: staging-test-2
content: "Run Performance Tests: Execute performance tests on staging environment"
status: pending
- id: staging-test-3
content: "Run Load Tests: Execute load tests on staging environment"
status: pending
- id: staging-test-4
content: "Monitor Staging Logs: Monitor logs for errors during testing period"
status: pending
- id: staging-test-5
content: "Verify Staging Health Endpoints: Test /health/live and /health/ready endpoints on staging"
status: pending
# Phase 5: Production Deployment
- id: prod-check-1
content: "Pre-production: Verify security audit passed - Review all security fixes are implemented"
status: pending
- id: prod-check-2
content: "Pre-production: Verify staging tests passed - Confirm all staging tests are successful"
status: pending
- id: prod-check-3
content: "Pre-production: Backup Database - Create database backup before production deployment"
status: pending
- id: prod-check-4
content: "Pre-production: Generate Production Secrets - Generate STRONG NON-DEFAULT JWT secrets for production"
status: pending
- id: prod-check-5
content: "Pre-production: Verify Critical Security Fixes - Confirm all CRITICAL security fixes are implemented and tested"
status: pending
- id: prod-k8s-1
content: "Create Production Namespace: kubectl create namespace production"
status: pending
- id: prod-k8s-2
content: "Create Production Secrets: kubectl create secret generic iam-service-secrets --from-literal=database-url='...' --from-literal=jwt-secret='STRONG_SECRET' --from-literal=jwt-refresh-secret='STRONG_SECRET' --from-literal=jwt-id-secret='STRONG_SECRET' -n production"
status: pending
- id: prod-k8s-3
content: "Apply Production ConfigMap: kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml"
status: pending
- id: prod-k8s-4
content: "Deploy Production Service: kubectl apply -f deployments/production/kubernetes/iam-service.yaml"
status: pending
- id: prod-k8s-5
content: "Deploy Production HPA: kubectl apply -f deployments/production/kubernetes/hpa.yaml"
status: pending
- id: prod-k8s-6
content: "Apply Production Ingress: kubectl apply -f deployments/production/kubernetes/ingress.yaml"
status: pending
- id: prod-migrate-1
content: "Run Production Migrations: DATABASE_URL='postgresql://...' pnpm prisma:deploy (safe deployment mode) - Verify migrations apply successfully"
status: pending
- id: prod-monitor-1
content: "Monitor Production Rollout: kubectl rollout status deployment/iam-service -n production - Verify deployment succeeds"
status: pending
- id: prod-monitor-2
content: "Check Production HPA: kubectl get hpa -n production - Verify HPA is configured correctly"
status: pending
- id: prod-security-1
content: "Production Security: Verify secrets NOT using defaults - Check all JWT secrets are strong and non-default"
status: pending
- id: prod-security-2
content: "Production Security: Verify TLS/SSL certificates configured - Check certificates are valid and configured"
status: pending
- id: prod-security-3
content: "Production Security: Verify network policies applied - Check Kubernetes network policies are in place"
status: pending
- id: prod-security-4
content: "Production Security: Verify pod security policies enabled - Check pod security policies are configured"
status: pending
- id: prod-security-5
content: "Production Security: Verify resource quotas set - Check resource quotas are configured for namespace"
status: pending
- id: prod-security-6
content: "Production Security: Verify RBAC configured - Check Kubernetes RBAC is properly configured"
status: pending
- id: prod-security-7
content: "Production Security: Verify monitoring alerts configured - Check Prometheus alerts are set up"
status: pending
- id: prod-security-8
content: "Production Security: Verify backup strategy in place - Confirm database backup strategy is implemented"
status: pending
# Phase 6: Post-deployment
- id: post-monitor-1
content: "Monitor Error Rates: Check error rates in monitoring dashboard, verify errors are within acceptable range"
status: pending
- id: post-monitor-2
content: "Monitor Response Times: Check API response times, verify performance metrics are acceptable"
status: pending
- id: post-monitor-3
content: "Check Security Events: Review audit logs for security events, verify no suspicious activities"
status: pending
- id: post-monitor-4
content: "Review Audit Logs: Review comprehensive audit logs for any anomalies"
status: pending
- id: post-monitor-5
content: "Verify Autoscaling: Monitor HPA scaling based on CPU/memory metrics, verify autoscaling works correctly"
status: pending
- id: post-test-1
content: "Test Failover Scenarios: Test pod failures, verify service remains available"
status: pending
- id: post-test-2
content: "Run Comprehensive Smoke Tests: Execute full smoke test suite on production"
status: pending
- id: post-test-3
content: "Verify Health Endpoints: Test /health/live and /health/ready endpoints on production"
status: pending
- id: post-test-4
content: "Test Authentication Flows: Test register, login, logout flows on production"
status: pending
- id: post-test-5
content: "Test Authorization Flows: Test RBAC/ABAC authorization on production"
status: pending
- id: post-doc-1
content: "Document Known Issues: Create document listing any known issues or limitations"
status: pending
- id: post-doc-2
content: "Create Operations Runbook: Create runbook with operational procedures, troubleshooting guides"
status: pending
- id: post-doc-3
content: "Update Deployment Procedures: Update deployment documentation with lessons learned"
status: pending
- id: post-doc-4
content: "Document Rollback Procedures: Document step-by-step rollback procedures for production"
status: pending
---
# IAM Service Audit Plan
## Tổng Quan (Overview)
Kế hoạch kiểm tra toàn diện cho IAM Service với 6 phases chính:
1. **Pre-deployment Audit**: Review logic nghiệp vụ, build, linting, testing
2. **Security Fixes (CRITICAL)**: Fix các lỗ hổng bảo mật nghiêm trọng
3. **Local Environment**: Setup và test môi trường local
4. **Staging Deployment**: Deploy và verify trên staging
5. **Production Deployment**: Deploy production với zero-downtime
6. **Post-deployment**: Monitor và validate sau deploy
---
## Phase 1: Pre-deployment Audit
### 1.1 Business Logic Review (10 Modules)
**Authentication Module** (`services/iam-service/src/modules/auth/`)
- Review registration flow: email validation, password hashing (bcrypt cost 12), user profile creation
- Review login flow: password verification, JWT generation (access + refresh), session creation, MFA integration
- Review token refresh: token family tracking, refresh token rotation, replay attack detection
- Review password change: refresh token revocation, audit logging
**Authorization/RBAC Module** (`services/iam-service/src/modules/rbac/`)
- Review permission resolution hierarchy: Direct user → Role → Group → Policy (ABAC)
- Review role assignment with expiration
- Review policy engine (JSON Logic)
- Validate permission caching (5 min TTL) và cache invalidation
**Identity Management** (`services/iam-service/src/modules/identity/`)
- User Management: CRUD operations, bulk import/export
- Profile Management: Custom fields, avatar upload/delete
- Verification: Email/phone/document verification flows
- Organizations: Multi-tenant support, hierarchical structure
- Groups: Member management, group-based permissions
**Access Management** (`services/iam-service/src/modules/access/`)
- Access Requests: Workflow, approval chains, JIT access
- Access Reviews: Certification campaigns, automated cleanup
- Access Analytics: Usage tracking, risk identification
**Multi-Factor Authentication** (`services/iam-service/src/modules/mfa/`)
- TOTP implementation (speakeasy library)
- QR code generation
- WebAuthn support
- Multiple devices per user
- MFA recovery flow (REVIEW REQUIRED - currently missing)
**Social Authentication** (`services/iam-service/src/modules/social/`)
- Google/Facebook/GitHub OAuth flows
- Account linking logic
- Token refresh for social providers
- Email verification bypass for verified social accounts
**OIDC Provider** (`services/iam-service/src/modules/oidc/`)
- Discovery endpoint
- Authorization code flow
- Token exchange
- JWKS endpoint
**Session Management** (`services/iam-service/src/modules/session/`)
- Device fingerprinting
- Session expiration
- Session revocation (single/all)
- Activity tracking
**Governance & Compliance** (`services/iam-service/src/modules/governance/`)
- Compliance reporting (GDPR, SOC2, ISO27001)
- Policy management và versioning
- Risk scoring (0-100)
- Audit reporting
**Cache và Event Sourcing** (`services/iam-service/src/core/cache/`, `services/iam-service/src/core/events/`)
- Multi-layer caching (L1: Memory, L2: Redis, L3: DB)
- Cache warming và invalidation
- Audit logging tất cả security events
- Event sourcing với 7-year retention
### 1.2 Build & Error Checking
**TypeScript Compilation**
```bash
cd services/iam-service
pnpm typecheck # Type checking
pnpm build # Full build
```
- Verify: No TypeScript errors, no unused variables/imports, type safety for Prisma models, path aliases (@/*) working
**Linting & Code Quality**
```bash
pnpm lint
```
- Verify: Coding standards compliance, no console.log in production code, proper error handling, no security anti-patterns
**Database Schema**
```bash
pnpm prisma:generate # Generate Prisma client
pnpm prisma:validate # Validate schema (if available)
```
- Verify: Schema syntax valid, all relations properly defined, indexes optimized, migration files consistent
**Testing**
```bash
pnpm test:unit # Unit tests
pnpm test:e2e # E2E tests
pnpm test:coverage # Coverage report
```
- Target: Coverage >= 70% (branches, functions, lines, statements), all critical paths tested
**Docker Build**
```bash
docker build -t iam-service:test -f services/iam-service/Dockerfile .
```
- Verify: Multi-stage build successful, image size <500MB, non-root user configured, health check functional
---
## Phase 2: Security Fixes (CRITICAL - Must Complete Before Production)
### 2.1 CRITICAL Vulnerabilities (HIGH PRIORITY)
**🔴 CRITICAL: MFA Secrets in Plaintext**
- **Location**: `services/iam-service/prisma/schema.prisma` (lines 23, 234)
- **Issue**: `MFADevice.secret``User.mfaSecret` stored unencrypted
- **Fix**: Implement field-level encryption using crypto module (encrypt before save, decrypt on read)
- **Files to modify**:
- `prisma/schema.prisma` - Add encrypted field support
- Create `services/iam-service/src/core/security/encryption.service.ts` for encryption/decryption
- Update `services/iam-service/src/modules/mfa/mfa.service.ts` to use encryption
**🔴 CRITICAL: Refresh Tokens in Plaintext**
- **Location**: `services/iam-service/prisma/schema.prisma` (line 177)
- **Issue**: `RefreshToken.token` stored as plaintext
- **Fix**: Store hashed tokens (SHA-256), compare hash during validation
- **Files to modify**:
- Update `services/iam-service/src/modules/token/jwt.service.ts` to hash refresh tokens before storing
- Update refresh token validation logic
**🔴 CRITICAL: Default JWT Secrets**
- **Location**: `services/iam-service/src/config/jwt.config.ts` (lines 7, 11, 15)
- **Issue**: Default secrets not blocked in production
- **Fix**: Add production check that throws error if defaults are used
- **Files to modify**:
- `services/iam-service/src/config/jwt.config.ts` - Add production validation
### 2.2 Medium Severity Issues
**🟡 Weak Input Sanitization**
- **Location**: `services/iam-service/src/utils/helpers.ts` (line 39)
- **Current**: Only removes `<` and `>`
- **Fix**: Use DOMPurify or proper HTML entity encoding
**🟡 No Password Complexity Rules**
- **Location**: `services/iam-service/src/modules/auth/auth.dto.ts` (line 9)
- **Current**: Only minimum 8 characters
- **Fix**: Enforce uppercase, lowercase, numbers, symbols
**🟡 Simple Device Fingerprinting**
- **Location**: `services/iam-service/src/modules/token/cookie.service.ts` (lines 117-126)
- **Current**: Basic User-Agent + IP hash
- **Fix**: Use @fingerprintjs/fingerprintjs library
**🟡 Missing Account Lockout**
- **Issue**: No protection after N failed login attempts
- **Fix**: Implement exponential backoff + account lockout
- **Files to create/modify**:
- Create `services/iam-service/src/modules/auth/account-lockout.service.ts`
- Update `services/iam-service/src/modules/auth/auth.service.ts` to track failed attempts
- Add `failedLoginAttempts``lockedUntil` fields to User model
### 2.3 Low Severity Issues
- No password history tracking
- CORS credentials enabled (review necessity)
- Social tokens in plaintext (consider encryption)
- No MFA backup codes
- Missing password breach checking (HaveIBeenPwned integration)
### 2.4 OWASP Top 10 Review
- A01: Broken Access Control - ✅ Well implemented via RBAC/ABAC
- A02: Cryptographic Failures - ❌ See vulnerabilities above
- A03: Injection - ✅ Protected by Prisma parameterized queries
- A04: Insecure Design - Review zero-trust implementation
- A05: Security Misconfiguration - Review Helmet.js settings
- A06: Vulnerable Components - Run `npm audit`
- A07: Auth Failures - ❌ Missing account lockout
- A08: Data Integrity Failures - Review JWT signature validation
- A09: Logging Failures - ✅ Comprehensive audit logging
- A10: SSRF - Review external API calls
---
## Phase 3: Local Environment Setup
### 3.1 Docker Compose Setup
**Environment Configuration**
- Copy `deployments/local/env.local.example` to `deployments/local/.env.local`
- Update environment variables:
- `DATABASE_URL` (Neon PostgreSQL)
- `REDIS_URL`
- `JWT_SECRET` (generate new, NOT default)
- `JWT_REFRESH_SECRET` (generate new)
- `JWT_ID_SECRET` (generate new)
- Social auth credentials
**Start Services**
```bash
cd deployments/local
docker-compose up -d
```
**Database Migrations**
```bash
cd services/iam-service
pnpm prisma:migrate
pnpm prisma:seed
```
**Verify Services**
- Traefik Dashboard: http://localhost:8080
- IAM Service: http://localhost:5001
- API Gateway: http://localhost/api/v1/auth
- Redis: localhost:6379
**Health Checks**
```bash
curl http://localhost:5001/health/live # Liveness
curl http://localhost:5001/health/ready # Readiness (includes DB)
curl http://localhost:5001/metrics # Prometheus metrics
```
### 3.2 Functional Testing
- Test authentication flows (register, login, logout)
- Test authorization (RBAC/ABAC)
- Test MFA (TOTP, WebAuthn)
- Test social login (Google, Facebook, GitHub)
- Review logs and metrics
---
## Phase 4: Staging Deployment
### 4.1 Kubernetes Setup
**Prerequisites**
- Kubernetes cluster configured
- kubectl installed và configured
- Docker images pushed to registry
**Create Namespace**
```bash
kubectl create namespace staging
```
**Create Secrets**
```bash
kubectl create secret generic iam-service-secrets \
--from-literal=database-url="postgresql://..." \
--from-literal=jwt-secret="..." \
--from-literal=jwt-refresh-secret="..." \
-n staging
```
**Apply ConfigMap**
```bash
kubectl apply -f deployments/staging/kubernetes/iam-service-configmap.yaml
```
**Deploy Service**
```bash
kubectl apply -f deployments/staging/kubernetes/iam-service.yaml
```
**Apply Ingress**
```bash
kubectl apply -f deployments/staging/kubernetes/ingress.yaml
```
**Run Migrations**
```bash
DATABASE_URL="postgresql://..." pnpm prisma:deploy
```
**Verify Deployment**
```bash
kubectl get pods -n staging
kubectl logs -f deployment/iam-service -n staging
kubectl describe pod <pod-name> -n staging
```
### 4.2 Configuration
- Replicas: 2
- Resources: Requests (256Mi memory, 250m CPU), Limits (512Mi memory, 500m CPU)
- Probes: Liveness (/health/live, 30s delay), Readiness (/health/ready, 10s delay)
### 4.3 Testing
- Smoke tests
- Performance testing
- Load testing
- Monitor logs for errors
---
## Phase 5: Production Deployment
### 5.1 Pre-deployment Checklist
- Security audit passed
- Staging tests passed
- Backup database
- Configure production secrets (NON-DEFAULT VALUES)
### 5.2 Kubernetes Setup
**Create Namespace**
```bash
kubectl create namespace production
```
**Create Secrets**
```bash
kubectl create secret generic iam-service-secrets \
--from-literal=database-url="postgresql://..." \
--from-literal=jwt-secret="STRONG_PRODUCTION_SECRET" \
--from-literal=jwt-refresh-secret="STRONG_PRODUCTION_REFRESH_SECRET" \
--from-literal=jwt-id-secret="STRONG_PRODUCTION_ID_SECRET" \
-n production
```
**Apply Production ConfigMap**
```bash
kubectl apply -f deployments/production/kubernetes/iam-service-configmap.yaml
```
**Deploy with HPA**
```bash
kubectl apply -f deployments/production/kubernetes/iam-service.yaml
kubectl apply -f deployments/production/kubernetes/hpa.yaml
```
**Apply Production Ingress**
```bash
kubectl apply -f deployments/production/kubernetes/ingress.yaml
```
**Run Migrations (Safe Deployment)**
```bash
DATABASE_URL="postgresql://..." pnpm prisma:deploy
```
**Monitor Rollout**
```bash
kubectl rollout status deployment/iam-service -n production
kubectl get hpa -n production
```
### 5.3 Production Configuration
- Replicas: 3 (min) → 10 (max) via HPA
- Resources: Requests (512Mi memory, 500m CPU), Limits (1Gi memory, 1000m CPU)
- Autoscaling: CPU target 70%, Memory target 80%
- Environment: `NODE_ENV=production`, `LOG_LEVEL=warn`, `TRACING_ENABLED=true`
### 5.4 Security Checklist
- ✅ Secrets NOT using defaults
- ✅ TLS/SSL certificates configured
- ✅ Network policies applied
- ✅ Pod security policies enabled
- ✅ Resource quotas set
- ✅ RBAC configured
- ✅ Monitoring alerts configured
- ✅ Backup strategy in place
---
## Phase 6: Post-deployment
### 6.1 Monitoring
- Monitor error rates
- Monitor response times
- Check for security events
- Review audit logs
- Verify autoscaling works
### 6.2 Testing
- Test failover scenarios
- Run comprehensive smoke tests
- Verify health endpoints
### 6.3 Documentation
- Document known issues
- Create runbook for operations
- Update deployment procedures
---
## Critical Files to Review/Modify
### Security Fixes Required
- `services/iam-service/prisma/schema.prisma` - Add encryption for sensitive fields
- `services/iam-service/src/config/jwt.config.ts` - Block defaults in production
- `services/iam-service/src/modules/auth/auth.dto.ts` - Password complexity
- `services/iam-service/src/modules/auth/auth.service.ts` - Account lockout
- `services/iam-service/src/utils/helpers.ts` - Input sanitization
- `services/iam-service/src/modules/token/cookie.service.ts` - Device fingerprinting
### Deployment Configs
- `deployments/local/docker-compose.yml`
- `deployments/staging/kubernetes/iam-service.yaml`
- `deployments/production/kubernetes/iam-service.yaml`
- `deployments/production/kubernetes/hpa.yaml`
---
## Conclusion
### Strengths
- ✅ Clean architecture với separation of concerns
- ✅ Comprehensive business logic (10 modules)
- ✅ Multi-layered security (RBAC + ABAC + Zero-Trust)
- ✅ Excellent audit logging
- ✅ Production-ready deployment configs
- ✅ CI/CD automation
- ✅ Horizontal scaling support
### Critical Issues to Address
- ❌ Encrypt sensitive data at rest (MFA secrets, refresh tokens)
- ❌ Block default JWT secrets in production
- ❌ Implement account lockout
- ❌ Improve password policies
- ❌ Enhanced input sanitization
### Recommendations
- **Immediate**: Fix all HIGH severity security issues before production
- **Short-term**: Implement MEDIUM severity fixes within 2 weeks
- **Long-term**: Enhance with ML-based risk analysis, passwordless auth
- **Continuous**: Regular security audits, penetration testing, dependency updates

View File

@@ -0,0 +1,660 @@
---
name: Điều chỉnh giao diện đa ngôn ngữ và hoàn thiện features cho web-admin
overview: Thiết lập hệ thống i18n hoàn chỉnh với next-intl cho web-admin, migrate tất cả hardcoded text sang translation files, tạo/copy UI components từ web-client để đảm bảo consistency, và hoàn thiện các features còn thiếu từ plan cũ (Analytics page, Messages page, API/Advanced settings tabs).
todos:
- id: install-deps
content: Cài đặt next-intl package - Update apps/web-admin/package.json và chạy pnpm install
status: completed
- id: create-i18n-config
content: Tạo apps/web-admin/src/i18n/config.ts - Định nghĩa locales ['en', 'vi'], default 'en'
status: completed
- id: create-i18n-request
content: Tạo apps/web-admin/src/i18n/request.ts - Request handler với locale detection logic
status: completed
- id: create-i18n-context
content: Tạo apps/web-admin/src/contexts/i18n-context.tsx - Context với setLocale, getLocale, localStorage sync, browser detection
status: completed
- id: create-i18n-provider
content: Tạo apps/web-admin/src/providers/i18n-provider.tsx - Provider component với static message imports (giống web-client fix)
status: completed
- id: create-translation-hook
content: Tạo apps/web-admin/src/hooks/use-translation.ts - Hook useTranslation() với type safety
status: completed
- id: update-root-layout
content: Update apps/web-admin/src/app/layout.tsx - Wrap với I18nProvider, dynamic lang attribute
status: completed
- id: copy-ui-button
content: Copy apps/web-client/src/components/ui/button.tsx sang apps/web-admin/src/components/ui/button.tsx
status: completed
- id: copy-ui-input
content: Copy apps/web-client/src/components/ui/input.tsx sang apps/web-admin/src/components/ui/input.tsx
status: completed
- id: copy-ui-card
content: Copy apps/web-client/src/components/ui/card.tsx sang apps/web-admin/src/components/ui/card.tsx
status: completed
- id: copy-ui-dialog
content: Copy apps/web-client/src/components/ui/dialog.tsx sang apps/web-admin/src/components/ui/dialog.tsx
status: completed
- id: copy-ui-avatar
content: Copy apps/web-client/src/components/ui/avatar.tsx sang apps/web-admin/src/components/ui/avatar.tsx
status: completed
- id: copy-ui-switch
content: Copy apps/web-client/src/components/ui/switch.tsx sang apps/web-admin/src/components/ui/switch.tsx
status: completed
- id: copy-ui-select
content: Copy apps/web-client/src/components/ui/select.tsx sang apps/web-admin/src/components/ui/select.tsx (nếu cần)
status: completed
- id: copy-ui-dropdown
content: Copy apps/web-client/src/components/ui/dropdown-menu.tsx sang apps/web-admin/src/components/ui/dropdown-menu.tsx (nếu cần)
status: completed
- id: extract-common-translations
content: Tạo translation keys cho common namespace - buttons, labels, placeholders (en.json + vi.json)
status: completed
- id: extract-auth-translations
content: Tạo translation keys cho auth namespace - login (en.json + vi.json)
status: completed
- id: extract-admin-dashboard-translations
content: Tạo translation keys cho admin.dashboard namespace - metrics, charts, activity table (en.json + vi.json)
status: completed
- id: extract-admin-users-translations
content: Tạo translation keys cho admin.users namespace - search, filters, table headers, actions, user details modal (en.json + vi.json)
status: completed
- id: extract-admin-analytics-translations
content: Tạo translation keys cho admin.analytics namespace - tabs, charts, metrics, reports (en.json + vi.json)
status: completed
- id: extract-admin-messages-translations
content: Tạo translation keys cho admin.messages namespace - message list, filters, moderation tools (en.json + vi.json)
status: completed
- id: extract-admin-settings-translations
content: Tạo translation keys cho admin.settings namespace - tabs, form labels, descriptions, General/Email/Security/API/Advanced (en.json + vi.json)
status: completed
- id: extract-validation-translations
content: Tạo translation keys cho validation namespace - form errors, Zod messages (en.json + vi.json)
status: completed
- id: extract-error-translations
content: Tạo translation keys cho errors namespace - API errors, general errors (en.json + vi.json)
status: completed
- id: migrate-login-page-ui
content: Migrate apps/web-admin/src/app/login/page.tsx - Replace hardcoded UI text với useTranslation()
status: completed
- id: migrate-login-validation
content: Update Zod schema trong login page - Sử dụng translated validation messages
status: completed
- id: migrate-dashboard-layout
content: Migrate apps/web-admin/src/app/(dashboard)/layout.tsx - Replace navigation labels với useTranslation()
status: completed
- id: migrate-dashboard-page-metrics
content: Migrate apps/web-admin/src/app/(dashboard)/dashboard/page.tsx - Replace metrics labels và values với useTranslation()
status: completed
- id: migrate-dashboard-page-charts
content: Migrate apps/web-admin/src/app/(dashboard)/dashboard/page.tsx - Replace chart labels và descriptions với useTranslation()
status: completed
- id: migrate-dashboard-page-activity
content: Migrate apps/web-admin/src/app/(dashboard)/dashboard/page.tsx - Replace activity table descriptions với useTranslation()
status: completed
- id: migrate-users-page-header
content: Migrate apps/web-admin/src/app/(dashboard)/users/page.tsx - Replace page header và description với useTranslation()
status: completed
- id: migrate-users-page-search-filters
content: Migrate apps/web-admin/src/app/(dashboard)/users/page.tsx - Replace search bar và filter labels với useTranslation()
status: completed
- id: migrate-users-page-table
content: Migrate apps/web-admin/src/app/(dashboard)/users/page.tsx - Replace table headers và actions với useTranslation()
status: completed
- id: migrate-settings-page
content: Migrate apps/web-admin/src/app/(dashboard)/settings/page.tsx - Replace tabs, headers, descriptions với useTranslation()
status: completed
- id: migrate-analytics-card
content: Migrate apps/web-admin/src/components/admin/analytics-card.tsx - Replace card labels, trend indicators với useTranslation()
status: completed
- id: migrate-data-table-headers
content: Migrate apps/web-admin/src/components/admin/data-table.tsx - Replace table headers và column labels với useTranslation()
status: completed
- id: migrate-data-table-pagination
content: Migrate apps/web-admin/src/components/admin/data-table.tsx - Replace pagination labels (Previous, Next, Page, etc.) với useTranslation()
status: completed
- id: migrate-data-table-actions
content: Migrate apps/web-admin/src/components/admin/data-table.tsx - Replace action buttons (Export, Select All, etc.) với useTranslation()
status: completed
- id: migrate-activity-table
content: Migrate apps/web-admin/src/components/admin/recent-activity-table.tsx - Replace activity descriptions, status labels với useTranslation()
status: completed
- id: migrate-user-details-modal-header
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace modal title, description với useTranslation()
status: completed
- id: migrate-user-details-modal-tabs
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace tab labels (Profile, Activity, Messages) với useTranslation()
status: completed
- id: migrate-user-details-modal-content
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace profile fields, activity descriptions, message history labels với useTranslation()
status: completed
- id: migrate-user-details-modal-actions
content: Migrate apps/web-admin/src/components/admin/user-details-modal.tsx - Replace action buttons (Edit, Delete, Ban, etc.) với useTranslation()
status: completed
- id: migrate-user-growth-chart
content: Migrate apps/web-admin/src/components/admin/charts/user-growth-chart.tsx - Replace chart labels, tooltips với useTranslation()
status: completed
- id: migrate-revenue-chart
content: Migrate apps/web-admin/src/components/admin/charts/revenue-chart.tsx - Replace chart labels, tooltips với useTranslation()
status: completed
- id: migrate-general-settings-ui
content: Migrate apps/web-admin/src/components/admin/settings/general-settings.tsx - Replace form labels, descriptions, buttons với useTranslation()
status: completed
- id: migrate-general-settings-validation
content: Update Zod schema trong general-settings.tsx - Sử dụng translated validation messages
status: completed
- id: migrate-email-settings-ui
content: Migrate apps/web-admin/src/components/admin/settings/email-settings.tsx - Replace form labels, descriptions, buttons với useTranslation()
status: completed
- id: migrate-email-settings-validation
content: Update Zod schema trong email-settings.tsx - Sử dụng translated validation messages
status: completed
- id: migrate-security-settings-ui
content: Migrate apps/web-admin/src/components/admin/settings/security-settings.tsx - Replace form labels, descriptions, policy texts với useTranslation()
status: completed
- id: migrate-security-settings-validation
content: Update Zod schema trong security-settings.tsx - Sử dụng translated validation messages
status: completed
- id: create-analytics-page-layout
content: Tạo apps/web-admin/src/app/(dashboard)/analytics/page.tsx - Page layout với tabs structure (Overview, Users, Messages, Performance)
status: completed
- id: create-analytics-overview-metrics
content: Tạo Overview tab - Key metrics summary cards với useTranslation()
status: completed
- id: create-analytics-overview-charts
content: Tạo Overview tab - Trends visualization và comparison charts với useTranslation()
status: completed
- id: create-analytics-users-funnel
content: Tạo Users tab - User acquisition funnel chart với useTranslation()
status: completed
- id: create-analytics-users-retention
content: Tạo Users tab - Retention chart và cohort analysis với useTranslation()
status: completed
- id: create-analytics-messages-stats
content: Tạo Messages tab - Total messages, average per user metrics với useTranslation()
status: completed
- id: create-analytics-messages-activity
content: Tạo Messages tab - Peak activity times chart với useTranslation()
status: completed
- id: create-analytics-performance-metrics
content: Tạo Performance tab - API response times, error rates metrics với useTranslation()
status: completed
- id: create-analytics-performance-uptime
content: Tạo Performance tab - Uptime statistics và charts với useTranslation()
status: completed
- id: create-messages-page-layout
content: Tạo apps/web-admin/src/app/(dashboard)/messages/page.tsx - Page layout với header, search, filters
status: completed
- id: create-messages-page-list
content: Tạo Messages page - Message list component với pagination và useTranslation()
status: completed
- id: create-messages-page-details
content: Tạo Messages page - Message details view component với useTranslation()
status: completed
- id: create-messages-page-moderation
content: Tạo Messages page - Content moderation tools với useTranslation()
status: completed
- id: create-messages-page-stats
content: Tạo Messages page - Message statistics cards với useTranslation()
status: completed
- id: create-api-settings-ui
content: Tạo apps/web-admin/src/components/admin/settings/api-settings.tsx - Form UI với API keys management, webhooks config, rate limits với useTranslation()
status: completed
- id: create-api-settings-validation
content: Tạo Zod schema cho api-settings.tsx - Sử dụng translated validation messages
status: completed
- id: create-advanced-settings-ui
content: Tạo apps/web-admin/src/components/admin/settings/advanced-settings.tsx - Form UI với feature flags, logs, cache, database settings với useTranslation()
status: completed
- id: create-advanced-settings-validation
content: Tạo Zod schema cho advanced-settings.tsx - Sử dụng translated validation messages
status: completed
- id: update-settings-tabs
content: Update apps/web-admin/src/app/(dashboard)/settings/page.tsx - Thêm API và Advanced tabs
status: completed
- id: integrate-language-preferences
content: Tích hợp language selector trong settings (nếu chưa có) - Kết nối với i18n context, trigger re-render
status: completed
- id: add-date-formatters-tables
content: Implement date formatting trong tables - Sử dụng locale cho date formatting trong data-table, activity-table
status: completed
- id: add-date-formatters-charts
content: Implement date formatting trong charts - Sử dụng locale cho date formatting trong user-growth-chart, revenue-chart
status: completed
- id: add-date-formatters-modals
content: Implement date formatting trong modals - Sử dụng locale cho date formatting trong user-details-modal
status: completed
- id: add-number-formatters
content: Implement number formatting - Sử dụng locale cho number formatting (nếu cần)
status: completed
- id: test-language-switching
content: Test language switching - Verify UI updates khi đổi ngôn ngữ
status: completed
- id: test-browser-detection
content: Test browser language detection - Verify auto-detect từ navigator.language
status: completed
- id: test-persistence
content: Test persistence - Verify language preference lưu trong localStorage và persist qua reload
status: completed
- id: test-all-pages-en
content: Test tất cả pages với English - Verify không có missing translations, UI hiển thị đúng
status: completed
- id: test-all-pages-vi
content: Test tất cả pages với Vietnamese - Verify không có missing translations, UI hiển thị đúng
status: completed
- id: verify-html-lang-attribute
content: Verify HTML lang attribute - Check <html lang> updates đúng khi đổi ngôn ngữ
status: completed
- id: test-validation-messages
content: Test validation messages - Verify form validation hiển thị đúng ngôn ngữ
status: completed
---
# Plan: Điều chỉnh giao diện đa ngôn ngữ và hoàn thiện features cho web-admin
## Tổng quan
Plan này sẽ:
- Setup next-intl cho Next.js App Router trong web-admin
- Tạo translation files cho en và vi với đầy đủ admin-specific translations
- Migrate tất cả hardcoded text "English / Tiếng Việt" sang translation system
- Tạo/copy UI components từ web-client để đảm bảo design system consistency
- Hoàn thiện các features còn thiếu: Analytics page, Messages page, API/Advanced settings tabs
- Tích hợp với language preferences từ localStorage
- Detect browser language cho user mới
- Update HTML lang attribute động
## Kiến trúc
```
apps/web-admin/
├── src/
│ ├── i18n/
│ │ ├── config.ts # Cấu hình next-intl
│ │ ├── request.ts # Request handler cho SSR
│ │ └── messages/
│ │ ├── en.json # English translations
│ │ └── vi.json # Vietnamese translations
│ ├── contexts/
│ │ └── i18n-context.tsx # Client-side i18n context
│ ├── hooks/
│ │ └── use-translation.ts # Custom hook cho translations
│ ├── providers/
│ │ └── i18n-provider.tsx # I18n provider component
│ └── components/
│ └── ui/ # UI components (copy từ web-client nếu cần)
│ ├── button.tsx
│ ├── input.tsx
│ ├── card.tsx
│ ├── dialog.tsx
│ ├── avatar.tsx
│ ├── switch.tsx
│ ├── select.tsx
│ └── dropdown-menu.tsx
```
## Các bước thực hiện
### Phase 1: Setup i18n Infrastructure
#### 1.1 Cài đặt dependencies
- Thêm `next-intl` vào `apps/web-admin/package.json`
- Chạy `pnpm install`
#### 1.2 Tạo cấu trúc i18n
- **File: `src/i18n/config.ts`** - Định nghĩa locales ['en', 'vi'], default 'en'
- **File: `src/i18n/request.ts`** - Request handler với locale detection logic
- **File: `src/i18n/messages/en.json`** - English translations với namespaces:
- `common`: buttons, labels, placeholders
- `auth`: login
- `admin`: dashboard, users, analytics, messages, settings
- `validation`: form validation messages
- `errors`: error messages
- **File: `src/i18n/messages/vi.json`** - Vietnamese translations với cùng structure
#### 1.3 Tạo I18n Context và Provider
- **File: `src/contexts/i18n-context.tsx`** - Context với setLocale, getLocale, localStorage sync, browser detection
- **File: `src/providers/i18n-provider.tsx`** - Provider component với dynamic message loading
- **File: `src/hooks/use-translation.ts`** - Custom hook useTranslation() với type safety
#### 1.4 Update Root Layout
- **File: `src/app/layout.tsx`** - Wrap với I18nProvider, dynamic lang attribute
### Phase 2: Tạo/Copy UI Components
#### 2.1 Copy UI Components từ web-client
Các components cần copy từ `apps/web-client/src/components/ui/` sang `apps/web-admin/src/components/ui/`:
- `button.tsx` - Button component với variants và sizes
- `input.tsx` - Input component với validation states
- `card.tsx` - Card component với subcomponents
- `dialog.tsx` - Dialog/Modal component
- `avatar.tsx` - Avatar component với sizes
- `switch.tsx` - Switch component
- `select.tsx` - Select component (nếu cần)
- `dropdown-menu.tsx` - Dropdown menu component (nếu cần)
**Lưu ý**: Các components này đang được import trong web-admin nhưng chưa tồn tại, cần tạo/copy để tránh lỗi.
### Phase 3: Extract và Tạo Translation Files
#### 3.1 Extract translations từ các pages/components hiện có
- **Common namespace**: buttons, labels, placeholders, loading states
- **Auth namespace**: login page texts
- **Admin namespace**:
- Dashboard: metrics, charts, activity table
- Users: search, filters, table headers, actions, user details modal
- Analytics: tabs, charts, metrics (nếu có)
- Messages: message management (nếu có)
- Settings: tabs, form labels, descriptions, General/Email/Security/API/Advanced settings
- **Validation namespace**: form errors, Zod messages
- **Errors namespace**: API errors, general errors
### Phase 4: Migrate Pages và Components
#### 4.1 Auth Pages
- **File: `src/app/login/page.tsx`** - Migrate hardcoded text, update validation schema
#### 4.2 Dashboard Pages
- **File: `src/app/(dashboard)/layout.tsx`** - Migrate sidebar navigation labels
- **File: `src/app/(dashboard)/dashboard/page.tsx`** - Migrate metrics, charts labels, activity descriptions
- **File: `src/app/(dashboard)/users/page.tsx`** - Migrate search, filters, table headers, actions
- **File: `src/app/(dashboard)/settings/page.tsx`** - Migrate tabs, headers, descriptions
#### 4.3 Admin Components
- **File: `src/components/admin/analytics-card.tsx`** - Migrate card labels, trend indicators
- **File: `src/components/admin/data-table.tsx`** - Migrate table headers, pagination, actions
- **File: `src/components/admin/recent-activity-table.tsx`** - Migrate activity descriptions, status labels
- **File: `src/components/admin/user-details-modal.tsx`** - Migrate modal content, tabs, actions
- **File: `src/components/admin/charts/user-growth-chart.tsx`** - Migrate chart labels, tooltips
- **File: `src/components/admin/charts/revenue-chart.tsx`** - Migrate chart labels, tooltips
- **File: `src/components/admin/settings/general-settings.tsx`** - Migrate form labels, validation, success/error messages
- **File: `src/components/admin/settings/email-settings.tsx`** - Migrate form labels, validation, test email messages
- **File: `src/components/admin/settings/security-settings.tsx`** - Migrate form labels, validation, security policy descriptions
### Phase 5: Hoàn thiện Features Còn Thiếu
#### 5.1 Analytics Page
- **File: `src/app/(dashboard)/analytics/page.tsx`** - Tạo mới với tabs:
- Overview tab: Key metrics summary, trends visualization, comparison charts
- Users tab: User acquisition funnel, retention chart, cohort analysis
- Messages tab: Total messages, average per user, peak activity times
- Performance tab: API response times, error rates, uptime statistics
- **Components**: Tạo các chart components cần thiết (pie chart, donut chart, heatmap)
#### 5.2 Messages Page
- **File: `src/app/(dashboard)/messages/page.tsx`** - Tạo mới với:
- Message list với search và filters
- Message details view
- Content moderation tools
- Message statistics
#### 5.3 API Settings Tab
- **File: `src/components/admin/settings/api-settings.tsx`** - Tạo mới với:
- API keys management
- Webhooks configuration
- Rate limits settings
- Documentation link
- **Update**: `src/app/(dashboard)/settings/page.tsx` - Thêm API tab
#### 5.4 Advanced Settings Tab
- **File: `src/components/admin/settings/advanced-settings.tsx`** - Tạo mới với:
- Feature flags
- System logs
- Cache management
- Database settings
- Backup/restore options
- **Update**: `src/app/(dashboard)/settings/page.tsx` - Thêm Advanced tab
### Phase 6: Integration và Testing
#### 6.1 Tích hợp Language Preferences
- Update settings page để có language selector (nếu chưa có)
- Kết nối với i18n context
- Trigger re-render khi đổi ngôn ngữ
#### 6.2 Date và Number Formatting
- Sử dụng locale cho date formatting trong tables, charts
- Format numbers theo locale (nếu cần)
#### 6.3 Testing
- Test language switching
- Test browser language detection
- Test persistence qua page reloads
- Test tất cả pages với cả 2 ngôn ngữ
- Verify HTML lang attribute updates
- Test validation messages
## Translation Structure Example
```json
{
"common": {
"save": "Save",
"cancel": "Cancel",
"loading": "Loading...",
"search": "Search",
"filter": "Filter",
"export": "Export"
},
"admin": {
"dashboard": {
"title": "Dashboard",
"totalUsers": "Total Users",
"totalMessages": "Total Messages",
"activeUsers": "Active Users",
"revenue": "Revenue"
},
"users": {
"title": "User Management",
"searchPlaceholder": "Search users...",
"role": "Role",
"status": "Status",
"actions": "Actions"
},
"settings": {
"title": "System Settings",
"general": "General",
"email": "Email",
"security": "Security",
"api": "API",
"advanced": "Advanced"
}
}
}
```
## Dependencies và Execution Order
### Dependencies Matrix
```
install-deps
└─> create-i18n-config
├─> create-i18n-request
├─> create-i18n-context
│ ├─> create-i18n-provider
│ │ └─> update-root-layout
│ └─> create-translation-hook
│ └─> [tất cả migration tasks]
└─> [tất cả translation extraction tasks]
└─> [tất cả migration tasks]
copy-ui-components
└─> [tất cả migration tasks sử dụng UI components]
create-missing-features
└─> [migrate các features mới]
```
### Execution Phases
**Phase 1 (Tuần tự):**
- Setup i18n infrastructure (config, context, provider, hook)
- Update root layout
**Phase 2 (Song song):**
- Copy UI components từ web-client
- Extract và tạo translation files cho tất cả namespaces
**Phase 3 (Song song, sau Phase 1+2):**
- Migrate auth pages
- Migrate dashboard pages
- Migrate admin components
- Migrate settings components
**Phase 4 (Sau migrations):**
- Tạo Analytics page
- Tạo Messages page
- Tạo API settings tab
- Tạo Advanced settings tab
**Phase 5 (Cuối cùng):**
- Integration tasks (language preferences, date formatting)
- Testing toàn bộ system
## Parallelization Opportunities
- **Translation extraction**: 5 namespaces có thể làm song song (common, auth, admin, validation, errors)
- **UI components copy**: 8 components có thể copy song song
- **Page migrations**: 5 pages có thể migrate song song
- **Component migrations**: 8+ components có thể migrate song song
- **New features**: Analytics, Messages, API/Advanced settings có thể làm song song
## Lưu ý kỹ thuật
1. **UI Components**: Copy từ web-client để đảm bảo design system consistency
2. **Static Imports**: Sử dụng static imports cho messages trong provider (giống web-client fix)
3. **Type Safety**: Sử dụng TypeScript để type-check translation keys
4. **Fallback**: Luôn có fallback về 'en' nếu translation key không tồn tại
5. **Browser Detection**: Sử dụng `navigator.language` để detect
6. **Admin-specific Translations**: Tạo namespace `admin` riêng cho admin-specific texts
## Phân chia Tasks cho Multiple Agents
### Agent Roles
1. **setup** - Setup infrastructure (phải làm trước, tuần tự)
- Cài đặt dependencies
- Tạo config, context, provider, hook
- Update root layout
2. **ui-components** - Copy UI components (có thể làm song song)
- Copy 8 UI components từ web-client sang web-admin
- Có thể chia theo component: button, input, card, dialog, avatar, switch, select, dropdown-menu
3. **translations** - Tạo translation files (có thể làm song song)
- Extract và tạo translation keys cho các namespaces
- Có thể chia theo namespace: common, auth, admin.dashboard, admin.users, admin.analytics, admin.messages, admin.settings, validation, errors
4. **migration-auth** - Migrate auth pages (có thể làm song song sau khi có infrastructure)
- Login page UI và validation schema
5. **migration-dashboard** - Migrate dashboard pages (có thể làm song song)
- Dashboard layout, dashboard page (metrics, charts, activity), users page (header, search/filters, table), settings page
- Có thể chia theo page hoặc theo phần trong page
6. **migration-components** - Migrate admin components (có thể làm song song)
- Analytics card, data table (headers, pagination, actions), activity table, user details modal (header, tabs, content, actions), charts, settings forms
7. **new-features** - Tạo features mới (có thể làm song song sau migrations)
- Analytics page (layout, overview, users, messages, performance tabs)
- Messages page (layout, list, details, moderation, stats)
- API settings (UI, validation)
- Advanced settings (UI, validation)
8. **integration** - Integration tasks (phải làm sau khi có migrations)
- Language preferences integration
- Date/number formatters (tables, charts, modals)
9. **testing** - Testing tasks (phải làm cuối)
- Test tất cả functionality
### Execution Order
**Phase 1 (Tuần tự):**
- `setup` agent làm tất cả infrastructure tasks theo thứ tự dependencies
**Phase 2 (Song song):**
- `ui-components` agent copy 8 components song song
- `translations` agent có thể làm tất cả translation extraction tasks cùng lúc (5 admin sub-namespaces + common + auth + validation + errors)
**Phase 3-6 (Song song, sau Phase 1+2):**
- `migration-auth`, `migration-dashboard`, `migration-components` có thể làm song song
- Mỗi agent làm các file độc lập của mình
**Phase 7 (Sau migrations):**
- `new-features` agent làm các features mới (có thể chia nhỏ theo feature)
**Phase 8 (Sau new features):**
- `integration` agent làm integration tasks
**Phase 9 (Cuối cùng):**
- `testing` agent test toàn bộ system
### Dependencies Matrix
```
install-deps
└─> create-i18n-config
├─> create-i18n-request
├─> create-i18n-context
│ ├─> create-i18n-provider
│ │ └─> update-root-layout
│ └─> create-translation-hook
│ └─> [tất cả migration tasks]
└─> [tất cả translation extraction tasks]
└─> [tất cả migration tasks]
copy-ui-components (song song)
└─> [tất cả migration tasks sử dụng UI components]
create-missing-features
└─> [migrate các features mới]
```
### Parallelization Opportunities
- **UI components copy**: 8 components có thể copy song song
- **Translation extraction**: 9 namespaces có thể làm song song (common, auth, admin.dashboard, admin.users, admin.analytics, admin.messages, admin.settings, validation, errors)
- **Page migrations**: 4 pages có thể migrate song song (login, dashboard, users, settings)
- **Component migrations**: 9+ components có thể migrate song song
- **New features**: Analytics (9 subtasks), Messages (5 subtasks), API/Advanced settings (4 subtasks) có thể làm song song
- **Testing**: Một số test cases có thể chạy song song (nhưng nên test tuần tự để dễ debug)