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

EREGCSC-2267 sanitize file names #1106

Merged
merged 3 commits into from
Dec 15, 2023
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
19 changes: 16 additions & 3 deletions solution/backend/file_manager/admin.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import re

import requests
from django import forms
from django.conf import settings
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from django.utils.text import slugify

from common.functions import establish_client
from content_search.functions import add_to_index
Expand Down Expand Up @@ -55,11 +56,23 @@ class UploadedFileAdmin(BaseAdmin):
"subjects": lambda: Subject.objects.all()
}

# Will remove any characters from file namess we do not want in it.
# Commas in file names causes issues in chrsome on downloads since we rename the file.
def clean_file_name(self, name):
bad_char = [";", "!", "?", "*", ":", ",", '"', '“', "'", r'/', '\\', '-',]
temp = ''
split_name = name.split('.')
extension = split_name.pop()
file_name = '.'.join(split_name)
for i in bad_char:
temp = temp + i
clean_name = re.sub(rf'[{temp}]', '', file_name).strip()
return f'{clean_name}.{extension}'

def save_model(self, request, obj, form, change):
path = form.cleaned_data.get("file_path")
if path:
file_name, extension = path._name.split('.')
obj.file_name = f"{slugify(file_name)}.{extension}"
obj.file_name = self.clean_file_name(path._name)
self.upload_file(path, obj)
super().save_model(request, obj, form, change)

Expand Down
14 changes: 14 additions & 0 deletions solution/backend/file_manager/tests/test_admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from file_manager.admin import UploadedFileAdmin


def test_extension():
file_name = 'blah.txt'
admin = UploadedFileAdmin
clean_name = admin.clean_file_name('', file_name)
file_name = 'weird name with "quotations".doc'
assert clean_name == 'blah.txt'
clean_name = admin.clean_file_name('', file_name)
assert clean_name == 'weird name with quotations.doc'
file_name = "random:;/!? .xls"
clean_name = admin.clean_file_name('', file_name)
assert clean_name == 'random.xls'
Loading