-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: Add filetype validation to API (#4213)
- Loading branch information
1 parent
de76aa6
commit b818e0c
Showing
3 changed files
with
135 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import multer from "multer"; | ||
import path from "path"; | ||
|
||
/** | ||
* 30mb to match limit set in frontend | ||
* See editor.planx.uk/src/@planx/components/shared/PrivateFileUpload/Dropzone.tsx | ||
*/ | ||
const FILE_SIZE_LIMIT = 30 * 1024 * 1024; | ||
|
||
/** | ||
* Should match MIME type restrictions in frontend | ||
* See editor.planx.uk/src/@planx/components/shared/PrivateFileUpload/Dropzone.tsx | ||
*/ | ||
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "application/pdf"]; | ||
const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"]; | ||
|
||
const validateExtension = (filename: string): boolean => { | ||
const extension = path.extname(filename).toLowerCase(); | ||
return ALLOWED_EXTENSIONS.includes(extension); | ||
}; | ||
|
||
/** | ||
* Filter out invalid files | ||
*/ | ||
const fileFilter: multer.Options["fileFilter"] = (_req, file, callback) => { | ||
const isValidMimeType = ALLOWED_MIME_TYPES.includes(file.mimetype); | ||
const isValidExtension = validateExtension(file.originalname); | ||
|
||
if (isValidMimeType && isValidExtension) { | ||
callback(null, true); | ||
} else { | ||
callback(new Error("Unsupported file type")); | ||
} | ||
}; | ||
|
||
const multerOptions: multer.Options = { | ||
limits: { | ||
fileSize: FILE_SIZE_LIMIT, | ||
}, | ||
fileFilter, | ||
}; | ||
|
||
export const useFileUpload = multer(multerOptions).single("file"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters