Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

(feat) Restrict attachments to configured allowed extensions #1584

Merged
merged 16 commits into from
Jan 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import AttachmentsGridOverview from './attachments-grid-overview.component';
import AttachmentsTableOverview from './attachments-table-overview.component';
import AttachmentPreview from './image-preview.component';
import styles from './attachments-overview.scss';
import { useAllowedExtensions } from './use-allowed-extensions';

const AttachmentsOverview: React.FC<{ patientUuid: string }> = ({ patientUuid }) => {
const { t } = useTranslation();
Expand All @@ -28,6 +29,7 @@ const AttachmentsOverview: React.FC<{ patientUuid: string }> = ({ patientUuid })
const [error, setError] = useState(false);
const [view, setView] = useState('grid');
const isTablet = useLayoutType() === 'tablet';
const { allowedExtensions } = useAllowedExtensions();

const closeImagePDFPreview = useCallback(() => setAttachmentToPreview(null), [setAttachmentToPreview]);

Expand All @@ -46,15 +48,15 @@ const AttachmentsOverview: React.FC<{ patientUuid: string }> = ({ patientUuid })
const showCam = useCallback(() => {
const close = showModal('capture-photo-modal', {
saveFile: (file: UploadedFile) => createAttachment(patientUuid, file),
allowedExtensions: allowedExtensions,
closeModal: () => {
close();
},
onCompletion: () => mutate(),
multipleFiles: true,
collectDescription: true,
allowedExtensions: ['image/jpeg', 'image/png', 'image/webp'],
});
}, [patientUuid, mutate]);
}, [patientUuid, mutate, allowedExtensions]);

const deleteAttachment = useCallback(
(attachment: Attachment) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import useSWRImmutable from 'swr/immutable';
import { openmrsFetch } from '@openmrs/esm-framework';

export interface GlobalProperty {
uuid: string;
property: string;
value: string;
}

/**
* Global property created by the openmrs-module-attachment
*/
const allowedExtensionsGlobalProperty: string = 'attachments.allowedFileExtensions';

/**
* React hook that takes returns the allowed file extensions
* @returns String array containing the `allowedExtensions`, `isLoading` loading status, `error`
*/
export const useAllowedExtensions = () => {
const customRepresentation = 'custom:(value)';
const { data, error, isLoading } = useSWRImmutable<{ data: { results: Array<GlobalProperty> } }>(
`/ws/rest/v1/systemsetting?&v=${customRepresentation}&q=${allowedExtensionsGlobalProperty}`,
openmrsFetch,
);

return {
isLoading,
allowedExtensions:
data?.data?.results?.length > 0 ? data?.data?.results[0].value?.toLowerCase().split(',') || undefined : undefined,
error: error,
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,19 @@ const MediaUploaderComponent = () => {
const upload = useCallback(
(files: Array<File>) => {
files.forEach((file) => {
if (file.size <= fileSize * 1024 * 1024) {
if (file.size > fileSize * 1024 * 1024) {
showSnackbar({
title: t('fileSizeLimitExceededText', 'File size limit exceeded'),
subtitle: `${file.name} ${t('fileSizeLimitExceeded', 'exceeds the file size of')} ${fileSize} MB`,
kind: 'error',
});
} else if (!isFileExtensionAllowed(file.name, allowedExtensions)) {
showSnackbar({
title: t('fileExtensionNotAllowedText', 'File extension is not allowed'),
subtitle: `${file.name} ${t('allowedExtensionsAre', 'Allowed extensions are:')} ${allowedExtensions}`,
kind: 'error',
});
} else {
// Changing MB to bytes
readFileAsString(file).then((base64Content) => {
setFilesToUpload((uriData) => [
Expand All @@ -30,18 +42,20 @@ const MediaUploaderComponent = () => {
},
]);
});
} else {
showSnackbar({
title: t('fileSizeLimitExceededText', 'File size limit exceeded'),
subtitle: `${file.name} ${t('fileSizeLimitExceeded', 'exceeds the file size of')} ${fileSize} MB`,
kind: 'error',
});
}
});
},
[setFilesToUpload, fileSize, t],
);

const isFileExtensionAllowed = (fileName: string, allowedExtensions: string[]): boolean => {
if (!allowedExtensions) {
return true;
}
const fileExtension = fileName.split('.').pop();
return allowedExtensions?.includes(fileExtension.toLowerCase());
};

return (
<div className="cds--file__container">
<p className="cds--label-description">
Expand All @@ -52,7 +66,7 @@ const MediaUploaderComponent = () => {
</p>
<div className={styles.uploadFile}>
<FileUploaderDropContainer
accept={allowedExtensions ?? ['*']}
accept={allowedExtensions?.map((ext) => '.' + ext) || ['*']}
labelText={t('fileSizeInstructions', 'Drag and drop files here or click to upload')}
tabIndex={0}
multiple={multipleFiles}
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/am.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "Add Attachment",
"addImage": "Add image +",
"addMoreAttachments": "Add more attachments",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "Enter caption",
"attachments": "Attachments",
"Attachments": "Attachments",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "This field is required",
"file": "File",
"fileDeleted": "File deleted",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "File name",
"fileSizeInstructions": "Drag and drop files here or click to upload",
"fileSizeLimitExceeded": "exceeds the file size of",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/ar.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "أضف مرفق",
"addImage": "أضف صورة +",
"addMoreAttachments": "أضف المزيد من المرفقات",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "أدخل الوصف",
"attachments": "المرفقات",
"Attachments": "المرفقات",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "هذا الحقل مطلوب",
"file": "ملف",
"fileDeleted": "تم حذف الملف",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "اسم الملف",
"fileSizeInstructions": "قم بسحب وإسقاط الملفات هنا أو انقر للتحميل",
"fileSizeLimitExceeded": "تجاوز حجم الملف المسموح به",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "Add Attachment",
"addImage": "Add image +",
"addMoreAttachments": "Add more attachments",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "Enter caption",
"attachments": "Attachments",
"Attachments": "Attachments",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "This field is required",
"file": "File",
"fileDeleted": "File deleted",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "File name",
"fileSizeInstructions": "Drag and drop files here or click to upload",
"fileSizeLimitExceeded": "exceeds the file size of",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/es.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "Añadir archivo adjunto",
"addImage": "Añadir imagen +",
"addMoreAttachments": "Añadir más archivos adjuntos",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "Introduzca título",
"attachments": "Archivos adjuntos",
"Attachments": "Archivos adjuntos",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "Este campo es obligatorio",
"file": "Archivo",
"fileDeleted": "Archivo eliminado",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "Nombre de archivo",
"fileSizeInstructions": "Arrastre y suelte archivos aquí o haga clic para cargar",
"fileSizeLimitExceeded": "supera el tamaño de archivo de",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "Add Attachment",
"addImage": "Ajouter une image",
"addMoreAttachments": "Ajouter plus de pièces jointes",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "Ajouter une légende pour l'image",
"attachments": "Pièces jointes",
"Attachments": "Pièces jointes",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "Ce champs est requis",
"file": "Fichier",
"fileDeleted": "Fichier supprimé",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "Nom du fichier",
"fileSizeInstructions": "Faites glisser et déposez les fichiers ici ou cliquez pour télécharger",
"fileSizeLimitExceeded": "dépasse la taille de fichier de",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/he.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "הוסף קובץ מצורף",
"addImage": "הוסף תמונה +",
"addMoreAttachments": "הוסף קבצים מצורפים נוספים",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "הכנס תיאור לתמונה",
"attachments": "קבצים מצורפים",
"Attachments": "קבצים מצורפים",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "שדה זה נדרש",
"file": "קובץ",
"fileDeleted": "קובץ נמחק",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "שם הקובץ",
"fileSizeInstructions": "גרור ושחרר קבצים לכאן או לחץ להעלאה",
"fileSizeLimitExceeded": "חריג מגודל הקובץ של",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/km.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "បន្ថែមឯកសារភ្ជាប់",
"addImage": "បន្ថែមរូបភាព +",
"addMoreAttachments": "បន្ថែមឯកសារភ្ជាប់បន្ថែម",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "បញ្ចូលចំណងជើងសម្រាប់រូបភាព",
"attachments": "ឯកសារភ្ជាប់",
"Attachments": "ឯកសារភ្ជាប់",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "ចន្លោះនេះត្រូវតែបំពេញ",
"file": "ឯកសារ",
"fileDeleted": "បានលុបឯកសារចោល",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "ឈ្មោះឯកសារ",
"fileSizeInstructions": "អូស និងទម្លាក់ឯកសារនៅទីនេះ ឬចុចដើម្បីផ្ទុកឡើង",
"fileSizeLimitExceeded": "លើសពីទំហំឯកសារ",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/zh.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "添加附件",
"addImage": "添加图像 +",
"addMoreAttachments": "增加更多附件",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "输入标题",
"attachments": "附件",
"Attachments": "附件",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "此字段为必填项",
"file": "文件",
"fileDeleted": "文件已删除",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "文件名",
"fileSizeInstructions": "拖放文件到此处或点击上传",
"fileSizeLimitExceeded": "exceeds the file size of",
Expand Down
2 changes: 2 additions & 0 deletions packages/esm-patient-attachments-app/translations/zh_CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"addAttachment_title": "添加附件",
"addImage": "添加图像 +",
"addMoreAttachments": "增加更多附件",
"allowedExtensionsAre": "Allowed extensions are:",
"attachmentCaptionInstruction": "输入标题",
"attachments": "附件",
"Attachments": "附件",
Expand All @@ -25,6 +26,7 @@
"fieldRequired": "此字段为必填项",
"file": "文件",
"fileDeleted": "文件已删除",
"fileExtensionNotAllowedText": "File extension is not allowed",
"fileName": "文件名",
"fileSizeInstructions": "拖放文件到此处或点击上传",
"fileSizeLimitExceeded": "exceeds the file size of",
Expand Down
Loading