Project

General

Profile

Feature #181

Updated by Chakkaphon Noinang (Jay) 13 days ago

* [x] 5002 = jobpost 
 * [x] 5003 = candidates 
 * [x] [ ] 5005 = document 
 * [x] 5006 = jobapplication 
 * [ ] 5007 = batch 
 * [ ] 5008 = candidate-consumer 
 * [ ] 5011 = job-appointment 
 * [ ] 5012 = notification 
 * [ ] xxxx = jobpost-consumer 


 # สร้างไฟล์ src/shared/utils/jwt.util.ts 
 ```javascript 
 export function decodeJwt<T = unknown>(token: string): T { 
   const parts = token.split("."); 

   if (parts.length !== 3) { 
     throw new Error("Invalid JWT format"); 
   } 

   const payload = parts[1]; 

   const decoded = Buffer.from( 
     payload.replace(/-/g, "+").replace(/_/g, "/"), 
     "base64", 
   ).toString("utf-8"); 

   return JSON.parse(decoded) as T; 
 } 

 ``` 

 # แก้ไฟล์ auth-context.decorator.ts 
 ```javascript 
 import { 
   createParamDecorator, 
   ExecutionContext, 
   UnauthorizedException, 
 } from "@nestjs/common"; 
 import type { Request } from "express"; 
 import type { JWTPayload } from "@shared/auth/jwt-payload.interface"; 
 import { decodeJwt } from "@shared/utils/jwt.util"; 

 export interface AuthContext { 
   userId: string; 
   userName: string; 
   group: string[]; 
 } 

 export const ExtractAuthContext = createParamDecorator( 
   (data: unknown, ctx: ExecutionContext): AuthContext => { 
     const request = ctx.switchToHttp().getRequest<Request>(); 

     // Extract token from Authorization header 
     const authHeader = request.headers.authorization; 
     if (!authHeader) { 
       throw new UnauthorizedException("Authorization header is required"); 
     } 

     const token = authHeader.replace("Bearer ", "").trim(); 
     if (!token) { 
       throw new UnauthorizedException("Token is required"); 
     } 

     const jwtPayload = decodeJwt<JWTPayload>(token); 

     if (!jwtPayload.sid || !jwtPayload.name || !jwtPayload.group) { 
       throw new UnauthorizedException("User detail not correct"); 
     } 

     // Return auth context 
     return { 
       userId: jwtPayload.sid, 
       userName: jwtPayload.name, 
       group: jwtPayload.group, 
     }; 
   }, 
 ); 

 ``` 

 # แก้ไฟล์ src/shared/auth/jwt-payload.interface.ts 
 ```javascript 
 export interface JWTPayload { 
   sid: string; 
   name: string; 
   group: string[]; 
 } 
 ``` 


 # วิธีใช้ pass value ตั้งแต่ controller เข้าไป 
 ```javascript 
 @ExtractAuthContext() authContext: AuthContext 
 ```

Back