2025-08-07 17:14:56 +07:00
|
|
|
import { RequestWithUserWebService } from "./user";
|
|
|
|
|
import { AppDataSource } from "../database/data-source";
|
|
|
|
|
import { ApiKey } from "../entities/ApiKey";
|
|
|
|
|
import * as express from "express";
|
|
|
|
|
|
|
|
|
|
import HttpError from "../interfaces/http-error";
|
|
|
|
|
import HttpStatus from "../interfaces/http-status";
|
|
|
|
|
|
|
|
|
|
// เพิ่มฟังก์ชันสำหรับจัดการ Web Service Authentication
|
|
|
|
|
export async function handleWebServiceAuth(request: express.Request) {
|
|
|
|
|
// ตัวอย่างการใช้ API Key
|
|
|
|
|
const apiKey = request.headers["x-api-key"] as string;
|
|
|
|
|
|
|
|
|
|
if (!apiKey) {
|
|
|
|
|
throw new HttpError(HttpStatus.UNAUTHORIZED, "ไม่พบข้อมูลสำหรับยืนยันตัวตน");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// ตรวจสอบ API Key กับฐานข้อมูล
|
|
|
|
|
const apiKeyData = await AppDataSource.getRepository(ApiKey).findOne({
|
2026-05-21 11:44:28 +07:00
|
|
|
select: {
|
|
|
|
|
id: true,
|
|
|
|
|
name: true,
|
|
|
|
|
keyApi: true,
|
|
|
|
|
accessType: true,
|
|
|
|
|
dnaRootId: true,
|
|
|
|
|
dnaChild1Id: true,
|
|
|
|
|
dnaChild2Id: true,
|
|
|
|
|
dnaChild3Id: true,
|
|
|
|
|
dnaChild4Id: true,
|
|
|
|
|
},
|
2025-08-07 17:14:56 +07:00
|
|
|
where: { keyApi: apiKey },
|
|
|
|
|
relations: ["apiNames"],
|
|
|
|
|
});
|
|
|
|
|
if (!apiKeyData) {
|
|
|
|
|
throw new HttpError(HttpStatus.UNAUTHORIZED, "ไม่สามารถยืนยันตัวตนได้");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// บันทึก log data สำหรับ web service
|
|
|
|
|
if (!request.app.locals.logData) {
|
|
|
|
|
request.app.locals.logData = {};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
request.app.locals.logData.id = apiKeyData.id;
|
|
|
|
|
request.app.locals.logData.name = apiKeyData.name;
|
|
|
|
|
request.app.locals.logData.accessApi = apiKeyData.apiNames.map((x) => x.id) ?? [];
|
|
|
|
|
|
|
|
|
|
// ส่งคืนข้อมูลผู้ใช้ที่ยืนยันตัวตน
|
|
|
|
|
return {
|
|
|
|
|
id: apiKeyData.id,
|
|
|
|
|
name: apiKeyData.name,
|
|
|
|
|
type: "web-service",
|
|
|
|
|
accessApi: apiKeyData.apiNames.map((x) => x.id) ?? [],
|
2026-05-21 11:44:28 +07:00
|
|
|
accessType: apiKeyData.accessType,
|
|
|
|
|
dnaRootId: apiKeyData.dnaRootId,
|
|
|
|
|
dnaChild1Id: apiKeyData.dnaChild1Id,
|
|
|
|
|
dnaChild2Id: apiKeyData.dnaChild2Id,
|
|
|
|
|
dnaChild3Id: apiKeyData.dnaChild3Id,
|
|
|
|
|
dnaChild4Id: apiKeyData.dnaChild4Id,
|
2025-08-07 17:14:56 +07:00
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export function isPermissionRequest(
|
|
|
|
|
request: RequestWithUserWebService,
|
|
|
|
|
apiId: string,
|
|
|
|
|
): Promise<boolean> {
|
|
|
|
|
// ฟังก์ชันนี้ใช้เพื่อตรวจสอบสิทธิ์ของผู้ใช้ที่ร้องขอ API โดยตรวจสอบว่า user มีสิทธิ์เข้าถึง API ที่ร้องขอหรือไม่
|
|
|
|
|
const hasPermission = request.user.accessApi.includes(apiId);
|
|
|
|
|
if (!hasPermission) {
|
|
|
|
|
throw new HttpError(HttpStatus.FORBIDDEN, "คุณไม่มีสิทธิ์เข้าถึง API นี้");
|
|
|
|
|
}
|
|
|
|
|
return Promise.resolve(hasPermission);
|
|
|
|
|
}
|