Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add hash to uploading images (#7453)

Iga Karbowiak083d0c79e6e6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 775d71f929..a0bbe2ec30 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -111,6 +111,7 @@ All notable, unreleased changes to this project will be documented in this file.
- `channel` from `DraftOrderInput` changed to channelId
- `channel` from `pluginUpdate` changed to channelId
- Order events performance - #7424 by tomaszszymanski129
+- Add hash to uploading images #7453 by @IKarbowiak
### Breaking
- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysocki
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index b5aea31627..3f78fdd72e 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -20,7 +20,7 @@ from ...account.types import Address, AddressInput, User
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.types import Upload
from ...core.types.common import AccountError, StaffError
-from ...core.utils import validate_image_file
+from ...core.utils import add_hash_to_file_name, validate_image_file
from ...decorators import staff_member_required
from ...utils.validators import check_for_duplicates
from ..utils import (
@@ -534,6 +534,7 @@ class UserAvatarUpdate(BaseMutation):
user = info.context.user
image_data = info.context.FILES.get(image)
validate_image_file(image_data, "image")
+ add_hash_to_file_name(image_data)
if user.avatar:
user.avatar.delete_sized_images()
diff --git a/saleor/graphql/account/tests/test_account.py b/saleor/graphql/account/tests/test_account.py
index 52585e3b5e..78618d4b67 100644
--- a/saleor/graphql/account/tests/test_account.py
+++ b/saleor/graphql/account/tests/test_account.py
@@ -1,3 +1,4 @@
+import os
import re
import uuid
from collections import defaultdict
@@ -4021,6 +4022,11 @@ def test_user_avatar_update_mutation(monkeypatch, staff_api_client, media_root):
assert data["user"]["avatar"]["url"].startswith(
"http://testserver/media/user-avatars/avatar"
)
+ img_name, format = os.path.splitext(image_file._name)
+ file_name = user.avatar.name
+ assert file_name != image_file._name
+ assert file_name.startswith(f"user-avatars/{img_name}")
+ assert file_name.endswith(format)
# The image creation should have triggered a warm-up
mock_create_thumbnails.assert_called_once_with(user_id=user.pk)
diff --git a/saleor/graphql/core/tests/test_core.py b/saleor/graphql/core/tests/test_core.py
index ceefd6fb23..74849e317c 100644
--- a/saleor/graphql/core/tests/test_core.py
+++ b/saleor/graphql/core/tests/test_core.py
@@ -1,3 +1,4 @@
+import os
from unittest.mock import patch
import django_filters
@@ -19,6 +20,7 @@ from ..filters import EnumFilter
from ..mutations import BaseMutation
from ..types import FilterInputObjectType
from ..utils import (
+ add_hash_to_file_name,
clean_seo_fields,
get_duplicated_values,
snake_to_camel_case,
@@ -322,3 +324,14 @@ def test_get_oembed_data_unsupported_media_provider(url):
ValidationError, match="Unsupported media provider or incorrect URL."
):
get_oembed_data(url, "media_url")
+
+
+def test_add_hash_to_file_name(image, media_root):
+ previous_file_name = image._name
+
+ add_hash_to_file_name(image)
+
+ assert previous_file_name != image._name
+ file_name, format = os.path.splitext(image._name)
+ assert image._name.startswith(file_name)
+ assert image._name.endswith(format)
diff --git a/saleor/graphql/core/utils/__init__.py b/saleor/graphql/core/utils/__init__.py
index cb8599ad63..9705595b5c 100644
--- a/saleor/graphql/core/utils/__init__.py
+++ b/saleor/graphql/core/utils/__init__.py
@@ -1,8 +1,11 @@
import binascii
+import os
+import secrets
from typing import TYPE_CHECKING, Type, Union
import graphene
from django.core.exceptions import ValidationError
+from django.core.files.uploadedfile import SimpleUploadedFile
from graphene import ObjectType
from ....core.utils import generate_unique_slug
@@ -118,3 +121,11 @@ def from_global_id_or_error(
{field: ValidationError(f"Must receive a {only_type} id.", code="invalid")}
)
return _type, _id
+
+
+def add_hash_to_file_name(file):
+ """Add unique text fragment to the file name to prevent file overriding."""
+ file_name, format = os.path.splitext(file._name)
+ hash = secrets.token_hex(nbytes=4)
+ new_name = f"{file_name}_{hash}{format}"
+ file._name = new_name
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 1989ca54f0..5ca139df86 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -41,6 +41,7 @@ from ...core.scalars import WeightScalar
from ...core.types import SeoInput, Upload
from ...core.types.common import CollectionError, ProductError
from ...core.utils import (
+ add_hash_to_file_name,
clean_seo_fields,
from_global_id_or_error,
get_duplicated_values,
@@ -112,6 +113,7 @@ class CategoryCreate(ModelMutation):
if data.get("background_image"):
image_data = info.context.FILES.get(data["background_image"])
validate_image_file(image_data, "background_image")
+ add_hash_to_file_name(image_data)
clean_seo_fields(cleaned_input)
return cleaned_input
@@ -218,6 +220,7 @@ class CollectionCreate(ModelMutation):
if data.get("background_image"):
image_data = info.context.FILES.get(data["background_image"])
validate_image_file(image_data, "background_image")
+ add_hash_to_file_name(image_data)
is_published = cleaned_input.get("is_published")
publication_date = cleaned_input.get("publication_date")
if is_published and not publication_date:
@@ -1309,6 +1312,7 @@ class ProductMediaCreate(BaseMutation):
if image:
image_data = info.context.FILES.get(image)
validate_image_file(image_data, "image")
+ add_hash_to_file_name(image_data)
media = product.media.create(
image=image_data, alt=alt, type=ProductMediaTypes.IMAGE
)
diff --git a/saleor/graphql/product/tests/test_category.py b/saleor/graphql/product/tests/test_category.py
index 56ad150db1..f9aa087ccd 100644
--- a/saleor/graphql/product/tests/test_category.py
+++ b/saleor/graphql/product/tests/test_category.py
@@ -1,3 +1,4 @@
+import os
from unittest.mock import Mock, patch
import graphene
@@ -349,6 +350,11 @@ def test_category_create_mutation(
assert not data["category"]["parent"]
category = Category.objects.get(name=category_name)
assert category.background_image.file
+ img_name, format = os.path.splitext(image_file._name)
+ file_name = category.background_image.name
+ assert file_name != image_file._name
+ assert file_name.startswith(f"category-backgrounds/{img_name}")
+ assert file_name.endswith(format)
mock_create_thumbnails.assert_called_once_with(category.pk)
assert data["category"]["backgroundImage"]["alt"] == image_alt
diff --git a/saleor/graphql/product/tests/test_collection.py b/saleor/graphql/product/tests/test_collection.py
index 3f4c13b143..6989e642fd 100644
--- a/saleor/graphql/product/tests/test_collection.py
+++ b/saleor/graphql/product/tests/test_collection.py
@@ -1,3 +1,4 @@
+import os
from unittest.mock import Mock, patch
import graphene
@@ -462,6 +463,11 @@ def test_create_collection(
assert data["products"]["totalCount"] == len(product_ids)
collection = Collection.objects.get(slug=slug)
assert collection.background_image.file
+ img_name, format = os.path.splitext(image_file._name)
+ file_name = collection.background_image.name
+ assert file_name != image_file._name
+ assert file_name.startswith(f"collection-backgrounds/{img_name}")
+ assert file_name.endswith(format)
mock_create_thumbnails.assert_called_once_with(collection.pk)
assert data["backgroundImage"]["alt"] == image_alt
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index ea15ec01d4..c88948ed5d 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -1,4 +1,5 @@
import json
+import os
from datetime import datetime, timedelta
from decimal import Decimal
from unittest.mock import ANY, Mock, patch
@@ -7345,6 +7346,11 @@ def test_product_media_create_mutation(
product.refresh_from_db()
product_image = product.media.last()
assert product_image.image.file
+ img_name, format = os.path.splitext(image_file._name)
+ file_name = product_image.image.name
+ assert file_name != image_file._name
+ assert file_name.startswith(f"products/{img_name}")
+ assert file_name.endswith(format)
# The image creation should have triggered a warm-up
mock_create_thumbnails.assert_called_once_with(product_image.pk)