add more input checks and format

This commit is contained in:
OxSaitama 2023-07-04 14:05:25 +02:00
parent 4e632e27ed
commit afec5a5cea
55 changed files with 298 additions and 288 deletions

View File

@ -24,13 +24,13 @@ export default class UserController extends ApiController {
try {
const code = req.params["code"];
if (!code) throw new Error("code is required");
const token = await fetch('https://qual-connexion.idnot.fr/IdPOAuth2/token/idnot_idp_v1', {method: 'POST'});
const token = await fetch("https://qual-connexion.idnot.fr/IdPOAuth2/token/idnot_idp_v1", { method: "POST" });
console.log(token);
//const user = await this.authService.getUserFromIdNotTokens(code!);
//success
this.httpSuccess(response);
} catch (error) {
console.log(error)
console.log(error);
this.httpInternalError(response);
return;
}
@ -49,7 +49,6 @@ export default class UserController extends ApiController {
//success
this.httpSuccess(response, { accessToken, refreshToken });
} catch (error) {
console.log(error);
this.httpInternalError(response);
return;
}

View File

@ -92,7 +92,7 @@ export default class DocumentTypesController extends ApiController {
const documentTypeEntity = DocumentType.hydrate<DocumentType>(req.body);
//validate user
await validateOrReject(documentTypeEntity, { groups: ["update"] });
await validateOrReject(documentTypeEntity, { groups: ["updateDocumentType"] });
//call service to get prisma entity
const documentTypeEntityUpdated = await this.documentTypesService.update(uid, documentTypeEntity);

View File

@ -9,7 +9,7 @@ import { validateOrReject } from "class-validator";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
import authHandler from "@App/middlewares/AuthHandler";
import ruleHandler from "@App/middlewares/RulesHandler";
import fileHandler from "@App/middlewares/FileHandler";
import fileHandler from "@App/middlewares/OfficeMembershipHandlers/FileHandler";
@Controller()
@Service()
@ -93,13 +93,8 @@ export default class FilesController extends ApiController {
const document = await this.documentService.getByUid(fileEntity.document!.uid!);
if(!document){
this.httpNotFoundRequest(response, "document not found");
return;
}
document.document_status = "DEPOSITED";
await this.documentService.update(document.uid!, document);
document!.document_status = "DEPOSITED";
await this.documentService.update(document!.uid!, document!);
//Hydrate ressource with prisma entity
const fileEntityHydrated = File.hydrate<File>(fileEntityCreated, {

View File

@ -14,7 +14,6 @@ import FilesController from "./api/super-admin/FilesController";
import RulesController from "./api/super-admin/RulesController";
import RolesController from "./api/super-admin/RolesController";
/**
* @description This allow to declare all controllers used in the application
*/

View File

@ -4,11 +4,11 @@ import { NextFunction, Request, Response } from "express";
import Container from "typedi";
export default function authHandler(req: Request, response: Response, next: NextFunction) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
response.sendStatus(HttpCodes.UNAUTHORIZED)
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
@ -18,8 +18,7 @@ export default function authHandler(req: Request, response: Response, next: Next
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
req.body.user = userPayload
req.body.user = userPayload;
next();
});
}

View File

@ -1,22 +0,0 @@
import { NextFunction, Request, Response } from "express";
import multer from "multer";
export default function fileHandler(req: Request, response: Response, next: NextFunction) {
const storage = multer.memoryStorage()
const upload = multer({storage:storage}).single('file');
// Here call the upload middleware of multer
upload(req, response, function (err) {
if (err instanceof multer.MulterError) {
// A Multer error occurred when uploading.
const err = new Error('Multer error');
return next(err)
} else if (err) {
// An unknown error occurred when uploading.
const err = new Error('Server Error')
return next(err)
}
next()
})
}

View File

@ -10,8 +10,9 @@ export default async function deedHandler(req: Request, response: Response, next
const uid = req.path && req.path.split("/")[5];
const documentTypes: DocumentType[] = req.body.document_types;
if (uid) {
const deedService = Container.get(DeedsService);
const deed = await deedService.getOneByUidWithOffice(uid!);
const deed = await deedService.getOneByUidWithOffice(uid);
if (!deed) {
response.sendStatus(HttpCodes.NOT_FOUND);
@ -22,6 +23,7 @@ export default async function deedHandler(req: Request, response: Response, next
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
}
if (documentTypes) {
const documentTypeService = Container.get(DocumentTypesService);

View File

@ -5,6 +5,7 @@ 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) {
const officeId = req.body.user.office_Id;
@ -12,10 +13,18 @@ export default async function documentHandler(req: Request, response: Response,
const documentType: DocumentType = req.body.document_type;
const folder: OfficeFolder = req.body.folder;
if (folder && folder.office?.uid != officeId) {
if (folder) {
const officeFolderService = Container.get(OfficeFoldersService);
const officeFolderWithOffice = await officeFolderService.getByUidWithOffice(folder.uid!);
if (!officeFolderWithOffice) {
response.sendStatus(HttpCodes.NOT_FOUND);
return;
}
if (officeFolderWithOffice.office?.uid != officeId) {
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
}
if (documentType) {
const documentTypeService = Container.get(DocumentTypesService);

View File

@ -1,18 +1,26 @@
import HttpCodes from "@Common/system/controller-pattern/HttpCodes";
import { NextFunction, Request, Response } from "express";
import Container from "typedi";
import { OfficeFolder } from "le-coffre-resources/dist/SuperAdmin";
import FilesService from "@Services/common/FilesService/FilesService";
import DocumentsService from "@Services/super-admin/DocumentsService/DocumentsService";
export default async function fileHandler(req: Request, response: Response, next: NextFunction) {
const officeId = req.body.user.office_Id;
let uid = req.path && req.path.split("/")[5];
const folder: OfficeFolder = req.body.document.folder;
const document = req.body.document;
if (folder && folder.office?.uid != officeId) {
if (document) {
const documentService = Container.get(DocumentsService);
const documentWithOffice = await documentService.getByUidWithOffice(document.uid!);
if (!documentWithOffice) {
response.sendStatus(HttpCodes.NOT_FOUND);
return;
}
if (documentWithOffice.folder.office?.uid != officeId) {
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
}
if (uid === "download") uid = req.path && req.path.split("/")[6];
@ -24,7 +32,6 @@ export default async function fileHandler(req: Request, response: Response, next
response.sendStatus(HttpCodes.NOT_FOUND);
return;
}
if (file.document.folder.office.uid != officeId) {
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;

View File

@ -32,7 +32,9 @@ export default async function folderHandler(req: Request, response: Response, ne
const officeFolderService = Container.get(OfficeFoldersService);
if (officeFolderNumber) {
const officeFoldersWithSameNumber = await officeFolderService.get({ where: { folder_number: officeFolderNumber, office: {uid: officeId}}});
const officeFoldersWithSameNumber = await officeFolderService.get({
where: { folder_number: officeFolderNumber, office: { uid: officeId } },
});
if (officeFoldersWithSameNumber.length) {
response.sendStatus(HttpCodes.BAD_REQUEST);
return;

View File

@ -3,20 +3,19 @@ import { NextFunction, Request, Response } from "express";
export default async function ruleHandler(req: Request, response: Response, next: NextFunction) {
const rules = req.body.user.rules;
const service = req.path && req.path.split('/')[4];
const namespace = req.path && req.path.split('/')[3];
const service = req.path && req.path.split("/")[4];
const namespace = req.path && req.path.split("/")[3];
const role = req.body.user.role;
if(namespace != 'notary' && role != namespace) {
if (namespace != "notary" && role != namespace) {
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
if(!rules.includes(req.method + ' ' + service)) {
if (!rules.includes(req.method + " " + service)) {
response.sendStatus(HttpCodes.UNAUTHORIZED);
return;
}
next();
}

View File

@ -86,8 +86,7 @@ export class BackendVariables {
try {
await validateOrReject(this, validationOptions);
}
catch(error) {
} catch (error) {
if (process.env["NODE_ENV"] === "development") {
throw error;
}

View File

@ -1,4 +1,4 @@
import 'module-alias/register';
import "module-alias/register";
import { EFolderStatus, EOfficeStatus, ECivility, ECustomerStatus, PrismaClient, Prisma } from "@prisma/client";
import User, {
Address,
@ -17,7 +17,6 @@ import User, {
export default async function main() {
const prisma = new PrismaClient();
const randomString = () => {
const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
let result = "";
@ -824,7 +823,6 @@ export default async function main() {
created_at: new Date(),
updated_at: new Date(),
},
];
const roles: Role[] = [
@ -851,7 +849,7 @@ export default async function main() {
created_at: new Date(),
updated_at: new Date(),
rules: rules.slice(0, 11),
}
},
];
const officeRoles: OfficeRole[] = [
@ -882,7 +880,7 @@ export default async function main() {
updated_at: new Date(),
office: offices[0]!,
rules: rules.slice(0, 11),
}
},
];
const users: User[] = [
@ -1385,12 +1383,12 @@ export default async function main() {
office_status: EOfficeStatus.DESACTIVATED,
},
});
; office.uid = officeCreated.uid;
office.uid = officeCreated.uid;
}
for (const rule of rules) {
const ruleCreated = await prisma.rules.create({
data: {
name: rule.name
name: rule.name,
},
});
rule.uid = ruleCreated.uid;
@ -1607,8 +1605,8 @@ export default async function main() {
connect: officeFolder.stakeholders?.map((stakeholder) => ({
uid: stakeholder.uid!,
})),
}
}
},
},
});
officeFolder.uid = officeFolderCreated.uid;
}

View File

@ -69,8 +69,8 @@ export default class DeedTypesRepository extends BaseRepository {
document_types: {
set: deedType.document_types?.map((documentType) => ({
uid: documentType.uid!,
}))
}
})),
},
},
};

View File

@ -102,7 +102,7 @@ export default class DeedsRepository extends BaseRepository {
include: {
deed_type: { include: { office: true } },
document_types: { include: { office: true } },
}
},
});
}
}

View File

@ -61,7 +61,7 @@ export default class DocumentTypesRepository extends BaseRepository {
uid: documentType.office!.uid,
},
},
}
},
};
return this.model.update(updateArgs);

View File

@ -78,7 +78,7 @@ export default class DocumentsRepository extends BaseRepository {
const batchPayload = await this.model.createMany(createArgs);
const documentsCreated = await this.model.findMany({orderBy: {created_at: 'desc'}, take: batchPayload.count});
const documentsCreated = await this.model.findMany({ orderBy: { created_at: "desc" }, take: batchPayload.count });
const createHistoryArgs: Prisma.DocumentHistoryCreateManyArgs = {
data: documentsCreated.map((document) => ({
@ -106,7 +106,7 @@ export default class DocumentsRepository extends BaseRepository {
document_status: EDocumentStatus[document.document_status as keyof typeof EDocumentStatus],
refused_reason: refusedReason,
},
}
},
},
});
}

View File

@ -39,8 +39,8 @@ export default class FilesRepository extends BaseRepository {
file_path: file.file_path,
mimetype: file.mimetype,
size: file.size,
key: key
}
key: key,
},
};
return this.model.create({ ...createArgs, include: { document: true } });
}
@ -58,8 +58,8 @@ export default class FilesRepository extends BaseRepository {
file_path: file.file_path,
mimetype: file.mimetype,
size: file.size,
key: key
}
key: key,
},
};
return this.model.update({ ...updateArgs, include: { document: true } });
}
@ -74,8 +74,8 @@ export default class FilesRepository extends BaseRepository {
},
data: {
key: null,
archived_at: new Date(Date.now())
}
archived_at: new Date(Date.now()),
},
};
return this.model.update({ ...updateArgs, include: { document: true } });
}

View File

@ -48,8 +48,8 @@ export default class OfficeFoldersRepository extends BaseRepository {
connect: officeFolder.stakeholders?.map((stakeholder) => ({
uid: stakeholder.uid!,
})),
}
}
},
},
};
return this.model.create({ ...createArgs, include: { stakeholders: true } });

View File

@ -30,7 +30,7 @@ export default class RulesRepository extends BaseRepository {
public async create(rule: Rule): Promise<Rules> {
const createArgs: Prisma.RulesCreateArgs = {
data: {
name: rule.name
name: rule.name,
},
};
@ -46,7 +46,7 @@ export default class RulesRepository extends BaseRepository {
uid: rule.uid,
},
data: {
name: rule.name
name: rule.name,
},
};

View File

@ -57,7 +57,7 @@ export default class UsersRepository extends BaseRepository {
email: user.contact!.email,
phone_number: user.contact?.phone_number,
cell_phone_number: user.contact!.cell_phone_number,
civility: ECivility[user.contact?.civility as keyof typeof ECivility]
civility: ECivility[user.contact?.civility as keyof typeof ECivility],
},
},
role: {
@ -130,7 +130,7 @@ export default class UsersRepository extends BaseRepository {
email: user.contact!.email,
phone_number: user.contact?.phone_number,
cell_phone_number: user.contact?.cell_phone_number,
civility: ECivility[user.contact?.civility as keyof typeof ECivility]
civility: ECivility[user.contact?.civility as keyof typeof ECivility],
},
},
},

View File

@ -21,10 +21,10 @@ export type OpenIdConfig = {
scopes_supported: string[];
issuer: string;
jwks_uri: string;
}
};
export default interface OpenIdInterface {
getOpenIdConfig(): Promise<OpenIdConfig>
getOpenIdConfig(): Promise<OpenIdConfig>;
verifyIdToken(signingKey: string): Promise<Payload>;
getSigningKeys(jwksUri: string): Promise<string[]>;
}

View File

@ -9,7 +9,6 @@ import errorHandler from "@App/middlewares/ErrorHandler";
import { BackendVariables } from "@Common/config/variables/Variables";
import multer from "multer";
const storage = multer.memoryStorage();
(async () => {
@ -24,7 +23,12 @@ const storage = multer.memoryStorage();
label,
port: parseInt(port),
rootUrl,
middlwares: [cors({ origin: "*" }), multer({storage:storage}).single('file'), bodyParser.urlencoded({ extended: true }), bodyParser.json()],
middlwares: [
cors({ origin: "*" }),
multer({ storage: storage }).single("file"),
bodyParser.urlencoded({ extended: true }),
bodyParser.json(),
],
errorHandler,
});

View File

@ -5,7 +5,6 @@ import crypto from "crypto";
@Service()
export default class CryptoService extends BaseService {
private static readonly CRYPTO_ALGORITHM = "aes-256-ctr";
constructor(protected variables: BackendVariables) {
@ -13,7 +12,7 @@ export default class CryptoService extends BaseService {
}
private getKey(key: string) {
return crypto.createHash('sha256').update(String(key)).digest('base64').slice(0, 32);
return crypto.createHash("sha256").update(String(key)).digest("base64").slice(0, 32);
}
/**

View File

@ -10,7 +10,6 @@ import {v4} from "uuid";
import { Files, Prisma } from "@prisma/client";
import fetch from "node-fetch";
@Service()
export default class FilesService extends BaseService {
constructor(
@ -66,11 +65,12 @@ export default class FilesService extends BaseService {
const key = v4();
const encryptedFile = await this.cryptoService.encrypt(fileData.buffer, key);
const upload = await this.ipfsService.pinFile(Readable.from(encryptedFile), fileData.originalname);
const fileToCreate: File = file;
let fileToCreate: File = file;
fileToCreate.file_name = fileData.originalname;
fileToCreate.file_path = this.variables.PINATA_GATEWAY.concat(upload.IpfsHash);
fileToCreate.mimetype = fileData.mimetype;
fileToCreate.size = fileData.size;
fileToCreate.archived_at = null;
return this.filesRepository.create(fileToCreate, key);
}

View File

@ -9,7 +9,7 @@ export default class FilesService extends BaseService {
private ipfsClient: pinataSDK;
constructor(protected variables: BackendVariables) {
super();
this.ipfsClient = new pinataSDK({ pinataApiKey: variables.PINATA_API_KEY, pinataSecretApiKey: variables.PINATA_API_SECRET })
this.ipfsClient = new pinataSDK({ pinataApiKey: variables.PINATA_API_KEY, pinataSecretApiKey: variables.PINATA_API_SECRET });
}
/**

View File

@ -20,7 +20,7 @@ export type OpenIdConfig = {
scopes_supported: string[];
issuer: string;
jwks_uri: string;
}
};
@Service()
export default class OpenIdService extends BaseService {

View File

@ -6,9 +6,7 @@ import { Service } from "typedi";
@Service()
export default class DeedTypesService extends BaseService {
constructor(
private deedTypeRepository: DeedTypesRepository,
) {
constructor(private deedTypeRepository: DeedTypesRepository) {
super();
}

View File

@ -7,13 +7,12 @@ import DeedTypesService from "../DeedTypesService/DeedTypesService";
import DeedsRepository from "@Repositories/DeedsRepository";
import { Prisma } from "@prisma/client";
@Service()
export default class OfficeFoldersService extends BaseService {
constructor(
private officeFoldersRepository: OfficeFoldersRepository,
private deedTypeService: DeedTypesService,
private deedRepository: DeedsRepository
private deedRepository: DeedsRepository,
) {
super();
}
@ -32,8 +31,8 @@ export default class OfficeFoldersService extends BaseService {
*/
public async create(officeFolderEntity: OfficeFolder): Promise<OfficeFolders> {
const deedType = await this.deedTypeService.getByUid(officeFolderEntity.deed!.deed_type!.uid!);
if(!deedType) throw new Error('deed type not found');
if(deedType.archived_at) throw new Error('deed type is archived');
if (!deedType) throw new Error("deed type not found");
if (deedType.archived_at) throw new Error("deed type is archived");
const deed = await this.deedRepository.create(officeFolderEntity.deed!);
officeFolderEntity.deed!.uid = deed.uid;
return this.officeFoldersRepository.create(officeFolderEntity);
@ -69,7 +68,7 @@ export default class OfficeFoldersService extends BaseService {
*/
public async delete(uid: string): Promise<OfficeFolders> {
const officeFolderEntity = await this.officeFoldersRepository.findOneByUid(uid, { customers: true });
if(!officeFolderEntity) throw new Error('office folder not found');
if (!officeFolderEntity) throw new Error("office folder not found");
const officeFolder = OfficeFolder.hydrate<OfficeFolder>(officeFolderEntity, { strategy: "excludeAll" });
if (officeFolder.customers?.length) {

View File

@ -151,7 +151,7 @@ describe("test update function", () => {
describe("test get function", () => {
it("should return an array of Customers", async () => {
const req = {}
const req = {};
const customers = await CustomersServiceTest.get(req);
// verify result typing

View File

@ -279,7 +279,10 @@ describe("test get function", () => {
expect(deedTypesForFirstOffice[0]?.archived_at).toBeNull();
expect(deedTypesForFirstOffice[0]?.office_uid).toEqual(office.uid);
const deedTypesForSecondOffice = await DeedTypeServiceTest.get({ where: { office: {uid: office_.uid} }, orderBy: { name: "asc" } });
const deedTypesForSecondOffice = await DeedTypeServiceTest.get({
where: { office: { uid: office_.uid } },
orderBy: { name: "asc" },
});
expect(deedTypesForSecondOffice.length).toEqual(2);

View File

@ -241,7 +241,10 @@ describe("test get function", () => {
});
it("should return an array of DocumentTypes per offices", async () => {
const documentTypesForFirstOffice = await DocumentTypesServiceTest.get({ where: { office: {uid : office.uid }}, orderBy: { name: "asc" } });
const documentTypesForFirstOffice = await DocumentTypesServiceTest.get({
where: { office: { uid: office.uid } },
orderBy: { name: "asc" },
});
expect(documentTypesForFirstOffice.length).toEqual(1);
@ -252,7 +255,10 @@ describe("test get function", () => {
expect(documentTypesForFirstOffice[0]?.archived_at).toBeNull();
expect(documentTypesForFirstOffice[0]?.office_uid).toEqual(office.uid);
const documentTypesForSecondOffice = await DocumentTypesServiceTest.get({ where: { office: {uid : office_.uid }}, orderBy: { name: "asc" } });
const documentTypesForSecondOffice = await DocumentTypesServiceTest.get({
where: { office: { uid: office_.uid } },
orderBy: { name: "asc" },
});
expect(documentTypesForSecondOffice.length).toEqual(2);

View File

@ -1,7 +1,18 @@
import "module-alias/register";
import "reflect-metadata";
import { PrismaClient } from "prisma/prisma-client";
import { customer, customer_, deedType, documentType, documentType_, office, officeFolder, officeFolder_, user, user_ } from "@Test/config/MockedData";
import {
customer,
customer_,
deedType,
documentType,
documentType_,
office,
officeFolder,
officeFolder_,
user,
user_,
} from "@Test/config/MockedData";
import Container from "typedi";
import OfficeFoldersRepository from "@Repositories/OfficeFoldersRepository";
import OfficeFolderService from "@Services/super-admin/OfficeFoldersService/OfficeFoldersService";
@ -12,7 +23,11 @@ import DeedsRepository from "@Repositories/DeedsRepository";
const prisma = new PrismaClient();
const OfficeFolderServiceTest = new OfficeFolderService(Container.get(OfficeFoldersRepository), Container.get(DeedTypesService), Container.get(DeedsRepository));
const OfficeFolderServiceTest = new OfficeFolderService(
Container.get(OfficeFoldersRepository),
Container.get(DeedTypesService),
Container.get(DeedsRepository),
);
beforeAll(async () => {
office.uid = (await initOffice(office)).uid;