refactor: rabbitmq implement

This commit is contained in:
Methapon2001 2023-11-27 09:45:30 +07:00
parent 24350a11a4
commit 3fc70daed0
No known key found for this signature in database
GPG key ID: 849924FEF46BD132
12 changed files with 676 additions and 545 deletions

View file

@ -14,32 +14,30 @@ const jwtVerify = createVerifier({
},
});
export function expressAuthentication(
export async function expressAuthentication(
request: express.Request,
securityName: string,
scopes?: string[],
) {
return new Promise(async (resolve, reject) => {
if (securityName !== "bearerAuth") reject(new Error("Unknown authentication method."));
if (process.env.AUTH_BYPASS) return { preferred_username: "bypassed" };
const token = request.headers["authorization"]?.includes("Bearer ")
? request.headers["authorization"].split(" ")[1]
: null;
if (securityName !== "bearerAuth") throw new Error("Unknown authentication method.");
if (!token) return reject(new HttpError(HttpStatusCode.UNAUTHORIZED, "No token provided."));
const token = request.headers["authorization"]?.includes("Bearer ")
? request.headers["authorization"].split(" ")[1]
: null;
const payload = await jwtVerify(token).catch((_) => null);
if (!token) throw new HttpError(HttpStatusCode.UNAUTHORIZED, "No token provided.");
if (!payload) {
return reject(new HttpError(HttpStatusCode.UNAUTHORIZED, "Invalid token provided."));
}
const payload = await jwtVerify(token).catch((_) => null);
if (scopes && !scopes.every((v) => payload.resource_access[payload.azp].roles.includes(v))) {
return reject(
new HttpError(HttpStatusCode.FORBIDDEN, "You are not allowed to perform this action."),
);
}
if (!payload) {
throw new HttpError(HttpStatusCode.UNAUTHORIZED, "Invalid token provided.");
}
return resolve(payload);
});
if (scopes && !scopes.some((v) => payload.resource_access[payload.azp].roles.includes(v))) {
throw new HttpError(HttpStatusCode.FORBIDDEN, "You are not allowed to perform this action.");
}
return payload;
}

View file

@ -1,38 +1,27 @@
import { EhrFolder } from "../interfaces/ehr-fs";
import * as Minio from "minio";
import minioClient from "../storage";
import minioClient from "../minio";
/**
* Remove slash at the start and ensure slash at the end of the path
* @param path - path to be check and ensure
* @returns path without / at start and end with trailing slash
*/
function safePath(path: string) {
return path.replace(/^\/|\/$/g, "") + "/";
}
/**
* Replace illegal character eg. ? % < > / \ : | that can't be in path with "-".
* Used when create folder / dir through api
* Replace illegal character eg. ? % < > / \ : | that can't be in path with other char with dash by default.
* @param path - string to check and replace
* @returns path with illegal character replaced with "-"
* @param replace - string to replace illegal character
* @returns illegal character replaced path
*/
export function replaceIllegalChars(path: string, replaceChar = "-") {
return path.replace(/[/\\?%*:|"<>]/g, replaceChar);
export function replaceIllegalChars(path: string, replace = "-") {
return path.replace(/[/\\?%*:|"<>]/g, replace);
}
/**
* Utility function to check for .keep file if it is exist or not.
* @returns true if .keep exist, false otherwise
* Check if folder really exist by using ".keep" object.
*/
export async function pathExist(path: string): Promise<boolean> {
return await minioClient
.statObject("ehr", `${safePath(path)}.keep`)
.then((_) => true)
.catch((e) => {
return Boolean(
await minioClient.statObject("ehr", `${path.replace(/^\/|\/$/g, "")}/.keep`).catch((e) => {
if (e.code === "NotFound") return false;
throw new Error("Object Storage Error");
});
throw new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์");
}),
);
}
/**
@ -40,55 +29,62 @@ export async function pathExist(path: string): Promise<boolean> {
* @param path - path to list
* @return list of folder with metadata
*/
export function listFolder(path?: string): Promise<EhrFolder[]> {
if (path) path = safePath(path);
export async function listFolder(bucket: string, path?: string): Promise<EhrFolder[]> {
if (path) path = `${path.replace(/^\/|\/$/g, "")}/`;
return new Promise((resolve, reject) => {
const folder: EhrFolder[] = [];
const stream = minioClient.listObjectsV2("ehr", path ?? "");
const list = await new Promise<{ pathname: string; name: string }[]>((resolve, reject) => {
const item: { pathname: string; name: string }[] = [];
const stream = minioClient.listObjectsV2(bucket, path ?? "");
stream.on("data", (v) => {
if (!(v && v.prefix)) return;
folder.push({
pathname: v.prefix,
name: v.prefix.slice(path?.length).split("/")[0],
createdAt: "N/A",
createdBy: "N/A",
});
});
stream.on("end", async () => {
for (let i = 0; i < folder.length; i++) {
const stat = await minioClient
.statObject("ehr", `${folder[i].pathname}.keep`)
.catch((e) => console.error(`Error List Folder: ${folder[i].pathname}`, e));
if (!stat) continue;
folder[i] = {
...folder[i],
createdAt: stat.metaData.createdat ?? "N/A",
createdBy: stat.metaData.createdby ?? "N/A",
};
if (v && v.prefix) {
item.push({
pathname: v.prefix,
name: v.prefix.slice(path?.length).split("/")[0],
});
}
resolve(folder);
});
stream.on("error", () => reject(new Error("Object storage error occured.")));
stream.on("end", () => resolve(item));
stream.on("error", () => reject(new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์")));
});
const folder = await Promise.all(
list.map(async (v) => {
// Get stat from hidden object that used to mark as folder as minio doesn't really have folder
const stat = await minioClient
.statObject(bucket, `${v.pathname}.keep`)
.catch((e) => console.error(`MinIO Error: ${e}`));
if (!stat) return undefined;
const { createdat, createdby } = stat.metaData;
return {
...v,
createdAt: createdat ?? "n/a",
createdBy: createdby ?? "n/a",
} satisfies EhrFolder;
}),
);
return folder.filter((v: (typeof folder)[number]): v is EhrFolder => !!v);
}
export async function listItem(path: string, recursive = false): Promise<Minio.BucketItem[]> {
export async function listItem(
bucket: string,
path: string,
recursive = false,
): Promise<Minio.BucketItem[]> {
return new Promise((resolve, reject) => {
const stream = minioClient.listObjectsV2("ehr", path, recursive);
const stream = minioClient.listObjectsV2(bucket, path, recursive);
const item: Minio.BucketItem[] = [];
stream.on("data", (v) => {
if (v && v.name) item.push(v);
});
stream.on("end", () => resolve(item));
stream.on("error", () => reject(new Error("Object storage error occured.")));
stream.on("error", () => reject(new Error("เกิดข้อผิดพลาดกับระบบจัดการไฟล์")));
});
}
export const copyCond = new Minio.CopyConditions();