Skip to content

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

Add anonymize plugin

Maciej Korycinski3169b7929793
diff --git a/.isort.cfg b/.isort.cfg
index 72a7c64739..13f594c986 100644
--- a/.isort.cfg
+++ b/.isort.cfg
@@ -1,2 +1,2 @@
[settings]
-known_third_party = PIL,babel,bleach,bootstrap4,braintree,bs4,captcha,celery,dj_database_url,dj_email_url,django,django_babel,django_cache_url,django_countries,django_elasticsearch_dsl,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,elasticsearch_dsl,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_django_optimizer,graphql,graphql_jwt,graphql_relay,html5lib,html_to_draftjs,i18naddress,impersonate,markdown,measurement,mptt,oauthlib,phonenumber_field,phonenumbers,prices,promise,pytest,razorpay,requests,sentry_sdk,six,social_core,storages,stripe,templated_email,text_unidecode,tqdm,versatileimagefield
+known_third_party = PIL,babel,bleach,bootstrap4,braintree,bs4,captcha,celery,dj_database_url,dj_email_url,django,django_babel,django_cache_url,django_countries,django_elasticsearch_dsl,django_filters,django_measurement,django_prices,django_prices_openexchangerates,django_prices_vatlayer,draftjs_sanitizer,elasticsearch_dsl,faker,freezegun,geolite2,google_measurement_protocol,graphene,graphene_django,graphene_django_optimizer,graphene_federation,graphql,graphql_jwt,graphql_relay,html5lib,html_to_draftjs,i18naddress,impersonate,markdown,measurement,mptt,oauthlib,phonenumber_field,phonenumbers,prices,promise,pytest,razorpay,requests,sentry_sdk,six,social_core,storages,stripe,templated_email,text_unidecode,tqdm,versatileimagefield
diff --git a/saleor/account/models.py b/saleor/account/models.py
index b34f44471e..584b4e6701 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -78,6 +78,8 @@ class Address(models.Model):
return self.full_name
def __eq__(self, other):
+ if not isinstance(other, Address):
+ return False
return self.as_data() == other.as_data()
__hash__ = models.Model.__hash__
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index b89973e62a..350116e00c 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,19 +1,10 @@
-import os
-import os.path
-import random
-
-from django.conf import settings
-from django.core.files import File
-
from ..checkout import AddressType
-
-AVATARS_PATH = os.path.join(
- settings.PROJECT_ROOT, "saleor", "static", "images", "avatars"
-)
+from ..extensions.manager import get_extensions_manager
def store_user_address(user, address, address_type):
"""Add address to user address book and set as default one."""
+ address = get_extensions_manager().change_user_address(user, address, address_type)
address_data = address.as_data()
address = user.addresses.filter(**address_data).first()
@@ -39,6 +30,8 @@ def set_user_default_shipping_address(user, address):
def change_user_default_address(user, address, address_type):
+ address = get_extensions_manager().change_user_address(user, address, address_type)
+ address.save()
if address_type == AddressType.BILLING:
if user.default_billing_address:
user.addresses.add(user.default_billing_address)
@@ -71,10 +64,3 @@ def get_user_last_name(user):
if user.default_billing_address:
return user.default_billing_address.last_name
return None
-
-
-def get_random_avatar():
- """Return random avatar picked from a pool of static avatars."""
- avatar_name = random.choice(os.listdir(AVATARS_PATH))
- avatar_path = os.path.join(AVATARS_PATH, avatar_name)
- return File(open(avatar_path, "rb"), name=avatar_name)
diff --git a/saleor/account/views.py b/saleor/account/views.py
index bc6db370ce..994b1b9177 100755
--- a/saleor/account/views.py
+++ b/saleor/account/views.py
@@ -132,7 +132,11 @@ def address_edit(request, pk):
request.POST or None, instance=address, country_code=address.country.code
)
if address_form.is_valid() and not preview:
- address_form.save()
+ address = address_form.save()
+ address = request.extensions.change_user_address(
+ request.user, address, address_type=None
+ )
+ address.save()
message = pgettext("Storefront message", "Address successfully updated.")
messages.success(request, message)
return HttpResponseRedirect(reverse("account:details") + "#addresses")
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 61ddb96d53..bf7296561e 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -1,5 +1,7 @@
import decimal
import logging
+import os
+import random
import socket
from json import JSONEncoder
from urllib.parse import urljoin
@@ -9,6 +11,7 @@ from django import forms
from django.conf import settings
from django.contrib.sites.models import Site
from django.core import serializers
+from django.core.files import File
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.utils.encoding import iri_to_uri, smart_text
@@ -21,7 +24,6 @@ from geolite2 import geolite2
from prices import MoneyRange
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
-from ...account.utils import get_random_avatar
from ...celeryconf import app
from ...core.i18n import COUNTRY_CODE_CHOICES
@@ -29,6 +31,11 @@ georeader = geolite2.reader()
logger = logging.getLogger(__name__)
+AVATARS_PATH = os.path.join(
+ settings.PROJECT_ROOT, "saleor", "static", "images", "avatars"
+)
+
+
class CategoryChoiceField(forms.ModelChoiceField):
def label_from_instance(self, obj):
# pylint: disable=W0212
@@ -212,3 +219,10 @@ def get_country_name_by_code(country_code):
def get_company_address():
return Site.objects.get_current().settings.company_address
+
+
+def get_random_avatar():
+ """Return random avatar picked from a pool of static avatars."""
+ avatar_name = random.choice(os.listdir(AVATARS_PATH))
+ avatar_path = os.path.join(AVATARS_PATH, avatar_name)
+ return File(open(avatar_path, "rb"), name=avatar_name)
diff --git a/saleor/extensions/base_plugin.py b/saleor/extensions/base_plugin.py
index 5f0a47960f..41ad1f5c3e 100644
--- a/saleor/extensions/base_plugin.py
+++ b/saleor/extensions/base_plugin.py
@@ -43,6 +43,15 @@ class BasePlugin:
self._cached_config = plugin_config
self.active = plugin_config.active
+ def change_user_address(
+ self,
+ user: "User",
+ address: "Address",
+ address_type: str,
+ previous_value: "Address",
+ ) -> "Address":
+ return NotImplemented
+
def calculate_checkout_total(
self,
checkout: "Checkout",
diff --git a/saleor/extensions/manager.py b/saleor/extensions/manager.py
index 07100bd028..d41c28d0c1 100644
--- a/saleor/extensions/manager.py
+++ b/saleor/extensions/manager.py
@@ -64,6 +64,14 @@ class ExtensionsManager(PaymentInterface):
return previous_value
return returned_value
+ def change_user_address(
+ self, user: "User", address: "Address", address_type: Optional[str]
+ ) -> "Address":
+ default_value = address
+ return self.__run_method_on_plugins(
+ "change_user_address", default_value, user, address, address_type
+ )
+
def calculate_checkout_total(
self, checkout: "Checkout", discounts: List["DiscountInfo"]
) -> TaxedMoney:
diff --git a/saleor/extensions/plugins/anonymize/__init__.py b/saleor/extensions/plugins/anonymize/__init__.py
new file mode 100644
index 0000000000..b3c624cb47
--- /dev/null
+++ b/saleor/extensions/plugins/anonymize/__init__.py
@@ -0,0 +1,38 @@
+def obfuscate_address(address):
+ address.first_name = obfuscate_string(address.first_name)
+ address.last_name = obfuscate_string(address.last_name)
+ address.company_name = obfuscate_string(address.company_name)
+ address.street_address_1 = obfuscate_string(address.street_address_1)
+ address.street_address_2 = obfuscate_string(address.street_address_2)
+ address.city = obfuscate_string(address.city)
+ address.postal_code = obfuscate_string(address.postal_code)
+ return address
+
+
+def obfuscate_email(value):
+ string_rep = str(value)
+ if string_rep.endswith("@example.com"):
+ return string_rep
+ if "@" not in str(string_rep):
+ return obfuscate_string(string_rep)
+ username = str(string_rep).split("@")[0]
+ return "%[email protected]" % str(username)[:3]
+
+
+def obfuscate_string(value):
+ if not value:
+ return ""
+
+ string_rep = str(value)
+ if len(string_rep) > 6:
+ slice_tail = min([3, len(string_rep) - 6]) * -1
+ return "%s...%s" % (string_rep[:3], string_rep[slice_tail:])
+ return "%s..." % string_rep[:3]
+
+
+def obfuscate_order(order):
+ order.user_email = obfuscate_email(order.user_email)
+ if order.shipping_address:
+ order.shipping_address = obfuscate_address(order.shipping_address)
+ if order.billing_address:
+ order.billing_address = obfuscate_address(order.billing_address)
diff --git a/saleor/extensions/plugins/anonymize/plugin.py b/saleor/extensions/plugins/anonymize/plugin.py
new file mode 100644
index 0000000000..2afb129cab
--- /dev/null
+++ b/saleor/extensions/plugins/anonymize/plugin.py
@@ -0,0 +1,47 @@
+from typing import TYPE_CHECKING, Any, Optional
+
+from ...base_plugin import BasePlugin
+from . import obfuscate_address, obfuscate_email, obfuscate_order
+
+if TYPE_CHECKING:
+ from ....account.models import Address, User
+ from ....order.models import Order
+
+
+class AnonymizePlugin(BasePlugin):
+ """Anonymize all user data in the checkout, user profile and its orders."""
+
+ PLUGIN_NAME = "Anonymize"
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.active = True
+
+ def change_user_address(
+ self,
+ user: "User",
+ address: "Address",
+ address_type: Optional[str],
+ previous_value: "Address",
+ ) -> "Address":
+ if address.phone:
+ address.phone = ""
+ return obfuscate_address(address)
+
+ def order_created(self, order: "Order", previous_value: Any):
+ obfuscate_order(order)
+ order.save()
+
+ def customer_created(self, customer: "User", previous_value: Any) -> Any:
+ customer.email = obfuscate_email(customer.email)
+ customer.save()
+
+ @classmethod
+ def _get_default_configuration(cls):
+ defaults = {
+ "name": cls.PLUGIN_NAME,
+ "description": "",
+ "active": True,
+ "configuration": None,
+ }
+ return defaults
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 4e85a88ae5..9071df51ce 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -357,10 +357,16 @@ class BaseCustomerCreate(ModelMutation, I18nMixin):
# FIXME: save address in user.addresses as well
default_shipping_address = cleaned_input.get(SHIPPING_ADDRESS_FIELD)
if default_shipping_address:
+ info.context.extensions.change_user_address(
+ instance, default_shipping_address, "shipping"
+ )
default_shipping_address.save()
instance.default_shipping_address = default_shipping_address
default_billing_address = cleaned_input.get(BILLING_ADDRESS_FIELD)
if default_billing_address:
+ info.context.extensions.change_user_address(
+ instance, default_billing_address, "billing"
+ )
default_billing_address.save()
instance.default_billing_address = default_billing_address
diff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.py
index 64e80937a4..2e9155cb25 100644
--- a/saleor/graphql/account/mutations/staff.py
+++ b/saleor/graphql/account/mutations/staff.py
@@ -8,9 +8,9 @@ from graphql_jwt.exceptions import PermissionDenied
from ....account import events as account_events, models, utils
from ....account.error_codes import AccountErrorCode
from ....account.thumbnails import create_user_avatar_thumbnails
-from ....account.utils import get_random_avatar
from ....checkout import AddressType
from ....core.permissions import get_permissions
+from ....core.utils import get_random_avatar
from ....core.utils.url import validate_storefront_url
from ....dashboard.emails import send_set_password_email_with_url
from ....dashboard.staff.utils import remove_staff_member
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index 758484ae15..f1496b84d8 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -16,8 +16,8 @@ from prices import Money
from saleor.account import events as account_events
from saleor.account.error_codes import AccountErrorCode
from saleor.account.models import Address, User
-from saleor.account.utils import get_random_avatar
from saleor.checkout import AddressType
+from saleor.core.utils import get_random_avatar
from saleor.graphql.account.mutations.base import INVALID_TOKEN
from saleor.graphql.account.mutations.staff import (
CustomerDelete,
diff --git a/tests/test_account.py b/tests/test_account.py
index 1d25de5e81..b091d8b4aa 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -19,12 +19,9 @@ from saleor.account import forms, i18n
from saleor.account.forms import FormWithReCaptcha, NameForm
from saleor.account.models import User
from saleor.account.templatetags.i18n_address_tags import format_address
-from saleor.account.utils import (
- get_random_avatar,
- get_user_first_name,
- get_user_last_name,
-)
+from saleor.account.utils import get_user_first_name, get_user_last_name
from saleor.account.validators import validate_possible_number
+from saleor.core.utils import get_random_avatar
@pytest.mark.parametrize("country", ["CN", "PL", "US", "IE"])