Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add anonymize plugin
Maciej Korycinski3169b7929793
diff --git a/.isort.cfg b/.isort.cfgindex 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,versatileimagefielddiff --git a/saleor/account/models.py b/saleor/account/models.pyindex b34f44471e..584b4e6701 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -78,6 +78,8 @@ class Address(models.Model):return self.full_namedef __eq__(self, other):+ if not isinstance(other, Address):+ return Falsereturn self.as_data() == other.as_data()__hash__ = models.Model.__hash__diff --git a/saleor/account/utils.py b/saleor/account/utils.pyindex 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_managerdef 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_namereturn 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.pyindex 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__.pyindex 61ddb96d53..bf7296561e 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -1,5 +1,7 @@import decimalimport logging+import os+import randomimport socketfrom json import JSONEncoderfrom urllib.parse import urljoin@@ -9,6 +11,7 @@ from django import formsfrom django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.core import serializers+from django.core.files import Filefrom django.core.paginator import InvalidPage, Paginatorfrom django.http import Http404from django.utils.encoding import iri_to_uri, smart_text@@ -21,7 +24,6 @@ from geolite2 import geolite2from prices import MoneyRangefrom versatileimagefield.image_warmer import VersatileImageFieldWarmer-from ...account.utils import get_random_avatarfrom ...celeryconf import appfrom ...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.pyindex 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_configself.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.pyindex 07100bd028..d41c28d0c1 100644--- a/saleor/extensions/manager.py+++ b/saleor/extensions/manager.py@@ -64,6 +64,14 @@ class ExtensionsManager(PaymentInterface):return previous_valuereturn 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__.pynew file mode 100644index 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.pynew file mode 100644index 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 defaultsdiff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.pyindex 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 welldefault_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_addressdefault_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_addressdiff --git a/saleor/graphql/account/mutations/staff.py b/saleor/graphql/account/mutations/staff.pyindex 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 PermissionDeniedfrom ....account import events as account_events, models, utilsfrom ....account.error_codes import AccountErrorCodefrom ....account.thumbnails import create_user_avatar_thumbnails-from ....account.utils import get_random_avatarfrom ....checkout import AddressTypefrom ....core.permissions import get_permissions+from ....core.utils import get_random_avatarfrom ....core.utils.url import validate_storefront_urlfrom ....dashboard.emails import send_set_password_email_with_urlfrom ....dashboard.staff.utils import remove_staff_memberdiff --git a/tests/api/test_account.py b/tests/api/test_account.pyindex 758484ae15..f1496b84d8 100644--- a/tests/api/test_account.py+++ b/tests/api/test_account.py@@ -16,8 +16,8 @@ from prices import Moneyfrom saleor.account import events as account_eventsfrom saleor.account.error_codes import AccountErrorCodefrom saleor.account.models import Address, User-from saleor.account.utils import get_random_avatarfrom saleor.checkout import AddressType+from saleor.core.utils import get_random_avatarfrom saleor.graphql.account.mutations.base import INVALID_TOKENfrom saleor.graphql.account.mutations.staff import (CustomerDelete,diff --git a/tests/test_account.py b/tests/test_account.pyindex 1d25de5e81..b091d8b4aa 100644--- a/tests/test_account.py+++ b/tests/test_account.py@@ -19,12 +19,9 @@ from saleor.account import forms, i18nfrom saleor.account.forms import FormWithReCaptcha, NameFormfrom saleor.account.models import Userfrom 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_namefrom saleor.account.validators import validate_possible_number+from saleor.core.utils import get_random_avatar@pytest.mark.parametrize("country", ["CN", "PL", "US", "IE"])