From 4c5cdfb13da80faa511d19e70e61d7d6895169c2 Mon Sep 17 00:00:00 2001 From: Gabriel De Los Rios Date: Tue, 10 Dec 2024 17:48:29 -0300 Subject: [PATCH] fix(pets): adds file ext validation on the server side --- app/services/pet_service.py | 9 +++++++-- app/utils/validators/validators.py | 9 +++++++-- 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/app/services/pet_service.py b/app/services/pet_service.py index 5cbbea8..fea7b56 100644 --- a/app/services/pet_service.py +++ b/app/services/pet_service.py @@ -14,6 +14,7 @@ from app.utils.errors.pets.pet_register_errors import PetRegisterError from app.utils.flash_message import FlashMessage from app.utils.helpers import pet_sex_id_to_str from app.utils.validators.pet_validators import PetValidators +from app.utils.validators.validators import Validators class PetService: @staticmethod @@ -54,14 +55,18 @@ class PetService: img = request.files['img'] img_url = None - if(request.files['img']): + if(img): try: + if not Validators.allowed_file_img(img.filename): + raise(PetRegisterError("Invalid image format")) cloudinary.config(cloud_name = os.environ.get('CLOUD_NAME'), api_key=os.getenv('API_KEY'), api_secret=os.getenv('API_SECRET')) upload_result = cloudinary.uploader.upload(img) img_url = upload_result['secure_url'] + except PetRegisterError as e: + flash(FlashMessage(e.message, AlertType.DANGER.value )) except: - print("err!") + print("error") try: name = PetValidators.is_valid_name(request.form.get('name')) diff --git a/app/utils/validators/validators.py b/app/utils/validators/validators.py index c076831..f879b22 100644 --- a/app/utils/validators/validators.py +++ b/app/utils/validators/validators.py @@ -1,6 +1,5 @@ import re from typing import Optional - class Validators: @staticmethod @@ -17,4 +16,10 @@ class Validators: float(value) return True except: - return False \ No newline at end of file + return False + + @staticmethod + def allowed_file_img(filename): + ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'webp'} + return '.' in filename and \ + filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS \ No newline at end of file