Skip to content

Commit 48d3469

Browse files
committed
Check both extension and mimetype while uploading or unzipping file
1 parent e7280b2 commit 48d3469

File tree

1 file changed

+27
-2
lines changed

1 file changed

+27
-2
lines changed

filemanager/__init__.py

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import re
1111
import tarfile
1212
import zipfile
13+
import magic
1314

1415
path_end = r'(?P<path>[\w\d_ -/.]*)$'
1516

@@ -186,6 +187,16 @@ def handle_form(self, form, files):
186187
for chunk in f.chunks():
187188
dest.write(chunk)
188189
f.close()
190+
mimetype = magic.from_file(filepath, mime=True)
191+
guessed_exts = mimetypes.guess_all_extensions(mimetype)
192+
guessed_exts = [ext[1:] for ext in guessed_exts]
193+
common = [ext for ext in guessed_exts if ext in self.extensions]
194+
if not common:
195+
os.remove(filepath)
196+
messages.append(
197+
"File type not allowed : "
198+
+ f.name
199+
)
189200
if len(messages) == 0:
190201
messages.append('All files uploaded successfully')
191202
elif action == 'add':
@@ -330,12 +341,26 @@ def handle_form(self, form, files):
330341
zip_ref = zipfile.ZipFile(filename, 'r')
331342
#zip_ref.extractall(self.basepath + self.current_path)
332343
directory = self.basepath + self.current_path
333-
[zip_ref.extract(file, directory) for file
334-
in zip_ref.namelist() if file.endswith(tuple(self.extensions))]
344+
for file in zip_ref.namelist():
345+
if file.endswith(tuple(self.extensions)):
346+
zip_ref.extract(file, directory)
347+
mimetype = magic.from_file(directory + file, mime=True)
348+
print directory + file
349+
guessed_exts = mimetypes.guess_all_extensions(mimetype)
350+
guessed_exts = [ext[1:] for ext in guessed_exts]
351+
common = [ext for ext in guessed_exts if ext in self.extensions]
352+
if not common:
353+
os.remove(directory+file)
354+
messages.append(
355+
"File in the zip is not allowed : "
356+
+ file
357+
)
335358
zip_ref.close()
336359
except Exception as e:
337360
print e
338361
messages.append('ERROR : Could not unzip the file.')
362+
if len(messages) == 0:
363+
messages.append('Extraction completed successfully.')
339364

340365
return messages
341366

0 commit comments

Comments
 (0)