Skip to content

Commit

Permalink
🐛 Afficher message d'erreur si taille de fichier uploadée dépasse la …
Browse files Browse the repository at this point in the history
…limite autorisée (#2736)

* 🐛 Afficher un message d'alerte sur la page du formulaire si une fichier dépasse la limite autorisée (100% legacy)

* Update packages/applications/legacy/src/controllers/upload.ts

Co-authored-by: Violette <[email protected]>

* 🐛 Message d'erreur si fichier plus gros que 25 Mo sur legacy

---------

Co-authored-by: Violette <[email protected]>
  • Loading branch information
HubM and VioMrqs authored Feb 14, 2025
1 parent 77ebf6b commit 4ea8711
Show file tree
Hide file tree
Showing 15 changed files with 133 additions and 17 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export class FileSizeLimitError extends Error {
constructor(message: string) {
super(message);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export * from './yupTransformations';
export * from './getCurrentUrl';
export * from './getPagination';
export * from './isSoumisAuxGF';
export * from './fileSizeLimitError';
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,14 @@ v1Router.post(
);
}

if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.GET_CORRIGER_DELAI_ACCORDE_PAGE(demandeDélaiId), {
error: request.errorFileSizeLimit,
}),
);
}

const fichierRéponse = request.file && {
contents: fs.createReadStream(request.file.path),
filename: `${Date.now()}-${request.file.originalname}`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,14 @@ v1Router.post(
},
},
async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.DEMANDER_DELAI(request.body.projectId), {
error: request.errorFileSizeLimit,
}),
);
}

const {
projectId,
justification,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { AccorderDateAchèvementAntérieureDateThéoriqueError } from '../../../
import asyncHandler from '../../helpers/asyncHandler';
import {
errorResponse,
FileSizeLimitError,
iso8601DateToDateYupTransformation,
RequestValidationErrorArray,
unauthorizedResponse,
Expand Down Expand Up @@ -57,6 +58,10 @@ v1Router.post(
);
}

if (request.errorFileSizeLimit) {
return errAsync(new FileSizeLimitError(request.errorFileSizeLimit));
}

const file = request.file && {
contents: fs.createReadStream(request.file.path),
filename: `${Date.now()}-${request.file.originalname}`,
Expand Down Expand Up @@ -100,6 +105,18 @@ v1Router.post(
return unauthorizedResponse({ request, response });
}

if (error instanceof FileSizeLimitError) {
return response.redirect(
addQueryParams(
routes.GET_DETAILS_DEMANDE_DELAI_PAGE(request.body.modificationRequestId),
{
...request.body,
error,
},
),
);
}

if (error instanceof RequestValidationErrorArray) {
return response.redirect(
addQueryParams(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,14 @@ v1Router.post(
),
},
async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.CHANGER_FOURNISSEUR(request.body.projectId), {
error: request.errorFileSizeLimit,
}),
);
}

const { user } = request;
const { projectId, evaluationCarbone, justification } = request.body;
const file = request.file && {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,20 @@ import { fr } from 'date-fns/locale';
import { mediator } from 'mediateur';
import { ModificationRequest, Project } from '../../infra/sequelize';

const FORMAT_DATE = 'DD/MM/YYYY';

v1Router.post(
routes.ADMIN_REPLY_TO_MODIFICATION_REQUEST,

upload.single('file'),
ensureRole(['admin', 'dgec-validateur', 'dreal']),
asyncHandler(async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.DEMANDE_PAGE_DETAILS(request.body.modificationRequestId), {
error: request.errorFileSizeLimit,
}),
);
}

const {
user: { role },
body: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ v1Router.post(
ensureRole('porteur-projet'),
upload.single('file'),
asyncHandler(async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.LISTE_PROJETS, {
error: request.errorFileSizeLimit,
}),
);
}

const { projectId } = request.body;

if (!validateUniqueId(projectId)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,14 @@ v1Router.post(
},
},
async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.GET_CHANGER_PRODUCTEUR(request.body.projetId), {
error: request.errorFileSizeLimit,
}),
);
}

const { user } = request;
const { projetId, justification, producteur } = request.body;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ v1Router.post(
),
},
async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.DEMANDER_CHANGEMENT_PUISSANCE(request.body.projectId), {
error: request.errorFileSizeLimit,
}),
);
}

const {
body: { projectId, puissance, justification },
user,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,19 @@ import { upload } from '../upload';
import { v1Router } from '../v1Router';
import { ProjetDéjàClasséError } from '../../modules/modificationRequest';

const FORMAT_DATE = 'DD/MM/YYYY';

v1Router.post(
routes.ADMIN_CORRECT_PROJECT_DATA_ACTION,
upload.single('file'),
ensureRole(['admin', 'dgec-validateur']),
asyncHandler(async (request, response) => {
if (request.errorFileSizeLimit) {
return response.redirect(
addQueryParams(routes.PROJECT_DETAILS(request.body.projectId), {
error: request.errorFileSizeLimit,
}),
);
}

if (request.body.numeroCRE || request.body.familleId || request.body.appelOffreAndPeriode) {
return response.redirect(
addQueryParams(routes.PROJECT_DETAILS(request.body.projectId), {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import fs from 'fs';
import { ensureRole, signalerDemandeDelai } from '../../config';
import { logger } from '../../core/utils';
import { errAsync, logger } from '../../core/utils';
import asyncHandler from '../helpers/asyncHandler';
import { UnauthorizedError } from '../../modules/shared';
import routes from '../../routes';
import {
errorResponse,
iso8601DateToDateYupTransformation,
RequestValidationError,
FileSizeLimitError,
unauthorizedResponse,
validateRequestBody,
} from '../helpers';
Expand Down Expand Up @@ -59,6 +60,10 @@ v1Router.post(
asyncHandler(async (request, response) => {
validateRequestBody(request.body, requestBodySchema)
.asyncAndThen((body) => {
if (request.errorFileSizeLimit) {
return errAsync(new FileSizeLimitError(request.errorFileSizeLimit));
}

const { projectId, decidedOn, status, notes, délaiCdc2022 } = body;
const { user: signaledBy } = request;

Expand Down Expand Up @@ -93,6 +98,15 @@ v1Router.post(
);
},
(error) => {
if (error instanceof FileSizeLimitError) {
return response.redirect(
addQueryParams(routes.ADMIN_SIGNALER_DEMANDE_DELAI_PAGE(request.body.projectId), {
...request.body,
error,
}),
);
}

if (error instanceof RequestValidationError) {
return response.redirect(
addQueryParams(routes.ADMIN_SIGNALER_DEMANDE_DELAI_PAGE(request.body.projectId), {
Expand Down
36 changes: 25 additions & 11 deletions packages/applications/legacy/src/controllers/upload.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import multer from 'multer';

import type core from 'express-serve-static-core';

import { promises as fs } from 'fs';
import { logger } from '../core/utils';

Expand All @@ -10,19 +13,30 @@ const uploadWithMulter = multer({
});

export const upload = {
single: (filename: string) => (req, res, next) => {
res.on('finish', async () => {
if (req.file) {
try {
await fs.unlink(req.file.path);
} catch (error) {
logger.error(error);
single:
(filename: string) => (req: core.Request, response: core.Response, next: core.NextFunction) => {
const uploadHandler = uploadWithMulter.single(filename);

uploadHandler(req, response, (err) => {
if (err) {
logger.error(err);
req.errorFileSizeLimit = `Le fichier ne doit pas dépasser ${FILE_SIZE_LIMIT_IN_MB} Mo`;
return next();
}
}
});

return uploadWithMulter.single(filename)(req, res, next);
},
response.on('finish', async () => {
if (req.file) {
try {
await fs.unlink(req.file.path);
} catch (error) {
logger.error(error);
}
}
});

next();
});
},
multiple: (filename?: string) => (req, res, next) => {
return filename
? uploadWithMulter.array(filename)(req, res, next)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ declare module 'express-serve-static-core' {
accountUrl: string;
permissions: Permission[];
};
errorFileSizeLimit?: string;
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import React from 'react';
import { Input, LabelDescription } from '../atoms';

const FILE_SIZE_LIMIT_IN_MB = 25;

type InputFileProps = {
id?: string;
name?: string;
Expand All @@ -27,7 +29,9 @@ export const InputFile = ({
disabled={disabled}
className={className}
/>
<LabelDescription className="italic">Taille maximale du fichier : 50 Mo</LabelDescription>
<LabelDescription className="italic">
Taille maximale du fichier : {FILE_SIZE_LIMIT_IN_MB} Mo
</LabelDescription>
</div>
);
};

0 comments on commit 4ea8711

Please sign in to comment.