Skip to content

Commit

Permalink
fix: check the file type being uploaded before performing upload (#2584)
Browse files Browse the repository at this point in the history
Check the file type being uploaded before performing upload
use typeguards to properly narrow types for conditional logic

---------

Signed-off-by: Martin Musale <martinmusale@microsoft.com>
Co-authored-by: Nickii Miaro <miaronkirote@gmail.com>
Co-authored-by: Gavin Barron <gavinbarron@microsoft.com>
  • Loading branch information
3 people authored Jul 27, 2023
1 parent 3106969 commit 7fb265c
Showing 1 changed file with 15 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@ interface FutureDataTransferItem extends DataTransferItem {
getAsEntry: typeof DataTransferItem.prototype.webkitGetAsEntry;
}

const isFutureDataTransferItem = (item: DataTransferItem): item is FutureDataTransferItem =>
'getAsEntry' in item && typeof item.getAsEntry === 'function';

const isDataTransferItem = (item: DataTransferItem | File): item is DataTransferItem =>
('getAsFile' in item && typeof item.getAsFile === 'function') ||
('webkitGetAsEntry' in item && typeof item.webkitGetAsEntry === 'function');

/**
* Upload conflict behavior status
*/
Expand Down Expand Up @@ -1160,13 +1167,10 @@ export class MgtFileUpload extends MgtBaseComponent {
let entry: FileSystemEntry;
const collectFilesItems: File[] = [];

for (const uploadFileItem of filesItems as DataTransferItemList) {
if (uploadFileItem.kind === 'file') {
// Defensive code to validate if function exists in Browser
// Collect all Folders into Array
const futureUpload = uploadFileItem as FutureDataTransferItem;
if (futureUpload.getAsEntry) {
entry = futureUpload.getAsEntry();
for (const uploadFileItem of filesItems) {
if (isDataTransferItem(uploadFileItem)) {
if (isFutureDataTransferItem(uploadFileItem)) {
entry = uploadFileItem.getAsEntry();
if (isFileSystemDirectoryEntry(entry)) {
folders.push(entry);
} else {
Expand All @@ -1187,22 +1191,19 @@ export class MgtFileUpload extends MgtBaseComponent {
collectFilesItems.push(file);
}
}
} else if ('function' == typeof uploadFileItem.getAsFile) {
} else {
const file = uploadFileItem.getAsFile();
if (file) {
this.writeFilePath(file, '');
collectFilesItems.push(file);
}
}
continue;
} else {
const fileItem = uploadFileItem.getAsFile();
if (fileItem) {
this.writeFilePath(fileItem, '');
collectFilesItems.push(fileItem);
}
this.writeFilePath(uploadFileItem, '');
collectFilesItems.push(uploadFileItem);
}
}

// Collect Files from folder
if (folders.length > 0) {
const folderFiles = await this.getFolderFiles(folders);
Expand Down

0 comments on commit 7fb265c

Please sign in to comment.