@Res() res: Response: nếu thêm mà ko dùng thì nest sẽ hiểu bạn đang dùng library-specific mode
whitelist = true, Tự động xóa fields không có trong DTO: https://docs.nestjs.com/techniques/validation ⇒ ko lưu các field ko validate vào database. Ví dụ: có 3 field: id, name, phone. Mà chỉ có 2 field id, name được validate decode thì trường phone sẽ ko update vào database. còn forbidNonWhitelisted = true, khi response trả về sẽ thông báo cho người dùng những field đang chưa được validate.
cấu trúc typescript constructor(private catsService: CatsService) {} vừa bơm injection vừa giúp khởi tạo CatsService
lệnh : nest g resource auth —no-spec giúp tạo module
@Public() : đánh dấu router api này ko cần token
privider như kiểu bạn muuốn xe gì, useClass tôi cần xe honda
Set global app(#### Enable authentication globally: https://docs.nestjs.com/recipes/passport#implementing-passport-local)
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},cách trên là cách set global app, còn cách 2 là cách set theo từng router:
@Post('profile')
@UseGuards(JwtAuthGuard) // dùng cái này
getProfile(@Request() req) {
return { profile: req.user };
}
Flow dùng passport: Request ↓ 1️⃣ canActivate(context) - LUÔN được gọi nhưng có thể ko cần implement dùng mặc định ↓ ├─ Custom logic (check @Public(), roles, etc.) │ ├─ return true → STOP (bypass authentication) │ └─ return false → STOP (reject request) │ └─ super.canActivate(context) → Gọi Passport AuthGuard ↓ 2️⃣ Extract credentials (token, username/password, etc.) ↓ 3️⃣ Verify credentials ↓ 4️⃣ Strategy.validate() - Transform payload to user ↓ 5️⃣ handleRequest(err, user, info) - ĐƯỢC GỌI Ở ĐÂY (hàm này có thể gọi hoặc không) ↓ 6️⃣ req.user = user ↓ Route Handler