251123:2300 Update T1
This commit is contained in:
@@ -0,0 +1,40 @@
|
||||
// File: src/common/services/crypto.service.ts
|
||||
// บันทึกการแก้ไข: Encryption/Decryption Utility (T1.1)
|
||||
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { ConfigService } from '@nestjs/config';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
@Injectable()
|
||||
export class CryptoService {
|
||||
private readonly algorithm = 'aes-256-cbc';
|
||||
private readonly key: Buffer;
|
||||
private readonly ivLength = 16;
|
||||
|
||||
constructor(private configService: ConfigService) {
|
||||
// Key ต้องมีขนาด 32 bytes (256 bits)
|
||||
const secret =
|
||||
this.configService.get<string>('APP_SECRET_KEY') ||
|
||||
'default-secret-key-32-chars-long!';
|
||||
this.key = crypto.scryptSync(secret, 'salt', 32);
|
||||
}
|
||||
|
||||
encrypt(text: string): string {
|
||||
const iv = crypto.randomBytes(this.ivLength);
|
||||
const cipher = crypto.createCipheriv(this.algorithm, this.key, iv);
|
||||
let encrypted = cipher.update(text, 'utf8', 'hex');
|
||||
encrypted += cipher.final('hex');
|
||||
return `${iv.toString('hex')}:${encrypted}`;
|
||||
}
|
||||
|
||||
decrypt(text: string): string {
|
||||
const [ivHex, encryptedHex] = text.split(':');
|
||||
if (!ivHex || !encryptedHex) return text;
|
||||
|
||||
const iv = Buffer.from(ivHex, 'hex');
|
||||
const decipher = crypto.createDecipheriv(this.algorithm, this.key, iv);
|
||||
let decrypted = decipher.update(encryptedHex, 'hex', 'utf8');
|
||||
decrypted += decipher.final('utf8');
|
||||
return decrypted;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
// File: src/common/services/request-context.service.ts
|
||||
// บันทึกการแก้ไข: เก็บ Context ระหว่าง Request (User, TraceID) (T1.1)
|
||||
|
||||
import { Injectable, Scope } from '@nestjs/common';
|
||||
import { AsyncLocalStorage } from 'async_hooks';
|
||||
|
||||
@Injectable({ scope: Scope.DEFAULT })
|
||||
export class RequestContextService {
|
||||
private static readonly cls = new AsyncLocalStorage<Map<string, any>>();
|
||||
|
||||
static run(fn: () => void) {
|
||||
this.cls.run(new Map(), fn);
|
||||
}
|
||||
|
||||
static set(key: string, value: any) {
|
||||
const store = this.cls.getStore();
|
||||
if (store) {
|
||||
store.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
static get<T>(key: string): T | undefined {
|
||||
const store = this.cls.getStore();
|
||||
return store?.get(key);
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
static get currentUserId(): number | null {
|
||||
return this.get('user_id') || null;
|
||||
}
|
||||
|
||||
static get requestId(): string | null {
|
||||
return this.get('request_id') || null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user