From 994b9ced2ad774b16e3bc0db713cb15562415a34 Mon Sep 17 00:00:00 2001 From: Methapon2001 <61303214+Methapon2001@users.noreply.github.com> Date: Thu, 18 Jul 2024 17:22:53 +0700 Subject: [PATCH] refactor: update auth setting --- src/middlewares/auth-provider/keycloak.ts | 21 +++++++++++++++------ tsoa.json | 7 ++++--- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/src/middlewares/auth-provider/keycloak.ts b/src/middlewares/auth-provider/keycloak.ts index f105bfc..c111e57 100644 --- a/src/middlewares/auth-provider/keycloak.ts +++ b/src/middlewares/auth-provider/keycloak.ts @@ -19,10 +19,14 @@ const jwtDecode = createDecoder(); export async function keycloakAuth(request: Express.Request, roles?: string[]) { const token = request.headers["authorization"]?.includes("Bearer ") ? request.headers["authorization"].split(" ")[1] - : request.headers["authorization"]; + : ""; if (!token) { - throw new HttpError(HttpStatus.UNAUTHORIZED, "ไม่พบข้อมูลสำหรับยืนยันตัวตน"); + throw new HttpError( + HttpStatus.UNAUTHORIZED, + "authorization data not found.", + "authDataNotFound", + ); } let payload: Record = {}; @@ -49,7 +53,7 @@ export async function keycloakAuth(request: Express.Request, roles?: string[]) { if (!roles.some((a: string) => payload.roles.includes(a))) { throw new HttpError( HttpStatus.FORBIDDEN, - "คุณไม่มีสิทธิในการเข้าถึงข้อมูลดังกล่าว", + "You do not have permission to access this resource.", "noPermission", ); } @@ -61,7 +65,7 @@ export async function keycloakAuth(request: Express.Request, roles?: string[]) { async function verifyOffline(token: string) { const payload = await jwtVerify(token).catch((_) => null); if (!payload) { - throw new HttpError(HttpStatus.UNAUTHORIZED, "ไม่สามารถยืนยันตัวตนได้"); + throw new HttpError(HttpStatus.UNAUTHORIZED, "Unauthorized.", "authFailed"); } return payload; } @@ -74,9 +78,14 @@ async function verifyOnline(token: string) { }, ).catch((e) => console.error(e)); - if (!res) throw new Error("ไม่สามารถเข้าถึงระบบยืนยันตัวตน"); + if (!res) + throw new HttpError( + HttpStatus.INTERNAL_SERVER_ERROR, + "Error authentication service.", + "authFailedFatal", + ); if (!res.ok) { - throw new HttpError(HttpStatus.UNAUTHORIZED, "ไม่สามารถยืนยันตัวตนได้"); + throw new HttpError(HttpStatus.UNAUTHORIZED, "Unauthorized.", "authFailed"); } return await jwtDecode(token); diff --git a/tsoa.json b/tsoa.json index b6acbc9..ca7209f 100644 --- a/tsoa.json +++ b/tsoa.json @@ -7,10 +7,10 @@ "specVersion": 3, "securityDefinitions": { "keycloak": { - "type": "apiKey", + "type": "http", "name": "Authorization", "description": "Keycloak Bearer Token", - "in": "header" + "scheme": "bearer" } }, "spec": { @@ -33,7 +33,8 @@ { "name": "Product Type" }, { "name": "Product" }, { "name": "Work" }, - { "name": "Service" } + { "name": "Service" }, + { "name": "Quotation" } ] } },