updated api web service
This commit is contained in:
parent
537d70a8f3
commit
e0de2ed251
5 changed files with 84 additions and 3 deletions
56
src/middlewares/authWebService.ts
Normal file
56
src/middlewares/authWebService.ts
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
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({
|
||||
select: { id: true, name: true, keyApi: true },
|
||||
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) ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue