From 7d6deb76edde8dce5414220586c1fde0ddebfc6e Mon Sep 17 00:00:00 2001 From: Frederick Muriuki Muriithi Date: Tue, 16 Jan 2024 12:33:04 +0300 Subject: Build a sha512 hash from the uploaded file's name and timestamp Build a sha512 message digest from the file's name and the timestamp of when the file was uploaded. This ensures that the filename is URL-safe, and reduces chances of name conflicts in the upload directory which could lead to data corruption when processing the files and saving the files into the database. --- qc_app/files.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) (limited to 'qc_app') diff --git a/qc_app/files.py b/qc_app/files.py index 0304296..205a39c 100644 --- a/qc_app/files.py +++ b/qc_app/files.py @@ -1,6 +1,8 @@ """Utilities to deal with uploaded files.""" +import hashlib from pathlib import Path from typing import Union +from datetime import datetime from werkzeug.utils import secure_filename from werkzeug.datastructures import FileStorage @@ -9,7 +11,10 @@ def save_file(fileobj: FileStorage, upload_dir: Path) -> Union[Path, bool]: """Save the uploaded file and return the path.""" if not bool(fileobj): return False - filename = Path(secure_filename(fileobj.filename)) # type: ignore[arg-type] + hashed_name = hashlib.sha512( + f"{fileobj.filename}::{datetime.now().isoformat()}".encode("utf8") + ).hexdigest() + filename = Path(secure_filename(hashed_name)) # type: ignore[arg-type] if not upload_dir.exists(): upload_dir.mkdir() -- cgit v1.2.3