import HttpCodes from "@Common/system/controller-pattern/HttpCodes"; import { DocumentType } from "le-coffre-resources/dist/SuperAdmin"; import { NextFunction, Request, Response } from "express"; import Container from "typedi"; import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin"; import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService"; import DocumentTypesService from "@Services/super-admin/DocumentTypesService/DocumentTypesService"; import OfficeFoldersService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService"; export default async function documentHandler(req: Request, response: Response, next: NextFunction) { try { const officeId = req.body.user.office_Id; const uid = req.path && req.path.split("/")[5]; const documentType: DocumentType = req.body.document_type; const folder: OfficeFolder = req.body.folder; if (folder) { const officeFolderService = Container.get(OfficeFoldersService); const officeFolderWithOffice = await officeFolderService.getByUidWithOffice(folder.uid!); if (!officeFolderWithOffice) { response.status(HttpCodes.NOT_FOUND).send("Folder not found"); return; } if (officeFolderWithOffice.office?.uid != officeId) { response.status(HttpCodes.UNAUTHORIZED).send("Unauthorized with this office"); return; } } if (documentType) { const documentTypeService = Container.get(DocumentTypesService); const documentTypeWithOffice = await documentTypeService.getByUidWithOffice(documentType.uid!); if (!documentTypeWithOffice) { response.status(HttpCodes.NOT_FOUND).send("Document type not found"); return; } if (documentTypeWithOffice.office?.uid != officeId) { response.status(HttpCodes.UNAUTHORIZED).send("Unauthorized with this office"); return; } } if (uid) { const documentService = Container.get(DocumentsService); const document = await documentService.getByUidWithOffice(uid!); if (!document) { response.sendStatus(HttpCodes.NOT_FOUND).send("Document not found"); return; } if (document.folder.office.uid != officeId) { response.sendStatus(HttpCodes.UNAUTHORIZED).send("Unauthorized with this office"); return; } } next(); } catch (error) { console.log(error); response.status(HttpCodes.INTERNAL_ERROR).send("Internal server error"); return; } }