Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Drop demo (#14835)
Filip Owczarek9b312dc4b703
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 04304d35cd..2fd76f4441 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,8 +17,8 @@ All notable, unreleased changes to this project will be documented in this file.### Other changes- Add missing descriptions to order module - #14845 by @DevilsAutumn-- Unify how undiscounted prices are handled in orders and checkouts - #14780 by @jakubkuc+- Drop demo - #14835 by @fowczarek# 3.18.0diff --git a/saleor/core/exceptions.py b/saleor/core/exceptions.pyindex 58ff148c6b..849d15c557 100644--- a/saleor/core/exceptions.py+++ b/saleor/core/exceptions.py@@ -44,13 +44,6 @@ class PreorderAllocationError(Exception):self.order_line = order_line-class ReadOnlyException(Exception):- def __init__(self, msg=None):- if msg is None:- msg = "API runs in read-only mode"- super().__init__(msg)--class ProductNotPublished(Exception):def __init__(self, context=None):super().__init__("Can't add unpublished product.")diff --git a/saleor/demo/__init__.py b/saleor/demo/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/demo/management/__init__.py b/saleor/demo/management/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/demo/management/commands/__init__.py b/saleor/demo/management/commands/__init__.pydeleted file mode 100644index e69de29bb2..0000000000diff --git a/saleor/demo/management/commands/populatedb.py b/saleor/demo/management/commands/populatedb.pydeleted file mode 100644index c01041aa3f..0000000000--- a/saleor/demo/management/commands/populatedb.py+++ /dev/null@@ -1,46 +0,0 @@-from django.conf import settings--from ....channel.models import Channel-from ....core.management.commands.populatedb import Command as PopulateDBCommand-from ....payment.gateways.braintree.plugin import BraintreeGatewayPlugin-from ....plugins.manager import get_plugins_manager---def configure_braintree():- braintree_api_key = getattr(settings, "BRAINTREE_API_KEY", "")- braintree_merchant_id = getattr(settings, "BRAINTREE_MERCHANT_ID", "")- braintree_secret = getattr(settings, "BRAINTREE_SECRET_API_KEY", "")-- if not (braintree_api_key and braintree_merchant_id and braintree_secret):- return False-- channels = Channel.objects.all()- manager = get_plugins_manager()- for channel in channels:- manager.save_plugin_configuration(- BraintreeGatewayPlugin.PLUGIN_ID,- channel.slug,- {- "active": True,- "configuration": [- {"name": "Public API key", "value": braintree_api_key},- {"name": "Merchant ID", "value": braintree_merchant_id},- {"name": "Secret API key", "value": braintree_secret},- {"name": "Use sandbox", "value": True},- ],- },- )- return True---class Command(PopulateDBCommand):- def handle(self, *args, **options):- super().handle(*args, **options)- is_configured = configure_braintree()- if is_configured:- self.stdout.write("Configured Braintree")- else:- self.stdout.write(- "Failed to configure Braintree. Check if proper environment variables "- "are set."- )diff --git a/saleor/demo/settings.py b/saleor/demo/settings.pydeleted file mode 100644index 8c576acffd..0000000000--- a/saleor/demo/settings.py+++ /dev/null@@ -1,96 +0,0 @@-"""Settings file to run Saleor in "demo" mode.--Behavior specific to the demo mode:-- block API mutations that require admin permission (read-only mode for the dashboard-app)-- turn on anonymization plugin to anonymize data provided by customers in the public-checkout mutations-- configure Braintree payment gateway in sandbox mode if necessary environment-variables are set (see the `saleor.core.utils.random_data.configure_braintree` function-for more details)-- use DemoGraphQLView to render modified version of Playground that includes an example-GraphQL query-"""--import logging-import os-import re--import sentry_sdk-from sentry_sdk.integrations.celery import CeleryIntegration-from sentry_sdk.integrations.django import DjangoIntegration-from sentry_sdk.integrations.logging import ignore_logger--from ..settings import * # noqa: F403--logger = logging.getLogger(__name__)---# Override urls to use different GraphQL view on demo-ROOT_URLCONF = "saleor.demo.urls"--PLUGINS += ["saleor.plugins.anonymize.plugin.AnonymizePlugin"] # noqa: F405--GRAPHQL_MIDDLEWARE.insert( # noqa: F405- 0, "saleor.graphql.middleware.ReadOnlyMiddleware"-)--BRAINTREE_API_KEY = os.environ.get("BRAINTREE_API_KEY")-BRAINTREE_MERCHANT_ID = os.environ.get("BRAINTREE_MERCHANT_ID")-BRAINTREE_SECRET_API_KEY = os.environ.get("BRAINTREE_SECRET_API_KEY")--if not (BRAINTREE_API_KEY and BRAINTREE_MERCHANT_ID and BRAINTREE_SECRET_API_KEY):- logger.warning(- "Some Braintree environment variables are missing. Set them to create the "- "sandbox configuration in the demo mode with `populatedb` command."- )--PWA_ORIGINS = get_list(os.environ.get("PWA_ORIGINS", "demo.saleor.io")) # noqa: F405-PWA_DASHBOARD_URL_RE = re.compile("^https?://[^/]+/dashboard/.*")--ROOT_EMAIL = os.environ.get("ROOT_EMAIL")--# Remove "saleor.core" and add it after adding "saleor.demo", to have "populatedb"-# command overridden when using demo settings-# (see saleor.demo.management.commands.populatedb).-INSTALLED_APPS.remove("saleor.core") # noqa: F405-INSTALLED_APPS += ["saleor.demo", "saleor.core"] # noqa: F405---def _get_project_name_from_url(url: str) -> str:- if PWA_DASHBOARD_URL_RE.match(url):- return "dashboard"- return "storefront"---def before_send(event: dict, _hint: dict):- request: dict = event["request"]- request_headers: dict = request["headers"]-- origin_url: str = request_headers.get("Origin", "")- referer_url: str = request_headers.get("Referer", "")-- event["tags"] = {"project": _get_project_name_from_url(referer_url)}- ev_logger_name: str = event.get("logger", "")-- if ev_logger_name != "saleor.graphql.errors.handled":- return event-- # RFC6454, origin is the triple: uri-scheme, uri-host[, uri-port]- if any(origin_url.endswith(pwa_origin) for pwa_origin in PWA_ORIGINS):- return event-- logger.info(f"Skipped error from ignored origin: {origin_url!r}")- return None---DEMO_SENTRY_DSN = os.environ.get("DEMO_SENTRY_DSN")-if DEMO_SENTRY_DSN:- sentry_sdk.init(- DEMO_SENTRY_DSN,- integrations=[CeleryIntegration(), DjangoIntegration()],- before_send=before_send,- )- ignore_logger("graphql.execution.utils")- ignore_logger("graphql.execution.executor")- ignore_logger("django.security.DisallowedHost")diff --git a/saleor/demo/urls.py b/saleor/demo/urls.pydeleted file mode 100644index 84f99fa26e..0000000000--- a/saleor/demo/urls.py+++ /dev/null@@ -1,12 +0,0 @@-from django.urls import path-from django.views.decorators.csrf import csrf_exempt--from ..graphql.api import schema-from ..urls import urlpatterns as core_urlpatterns-from .views import DemoGraphQLView--urlpatterns = [- path("graphql/", csrf_exempt(DemoGraphQLView.as_view(schema=schema)), name="api"),-]--urlpatterns += core_urlpatternsdiff --git a/saleor/demo/views.py b/saleor/demo/views.pydeleted file mode 100644index d51ab6c576..0000000000--- a/saleor/demo/views.py+++ /dev/null@@ -1,35 +0,0 @@-from django.conf import settings-from django.shortcuts import render--from ..graphql.views import GraphQLView--EXAMPLE_QUERY = f"""# Welcome to Saleor GraphQL API!-#-# Type queries into this side of the screen, and you will see-# intelligent typeaheads aware of the current GraphQL type schema-# and live syntax and validation errors highlighted within the text.-#-# Here is an example query to fetch a list of products:-#-{{- products(first: 5, channel: "{settings.DEFAULT_CHANNEL_SLUG}") {{- edges {{- node {{- id- name- description- }}- }}- }}-}}-"""---class DemoGraphQLView(GraphQLView):- def render_playground(self, request):- pwa_origin = settings.PWA_ORIGINS[0] # type: ignore[misc] # set only in demo settings # noqa: E501- ctx = {- "query": EXAMPLE_QUERY,- "api_url": f"https://{pwa_origin}/graphql/",- }- return render(request, "graphql/playground.html", ctx)diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.pyindex 040430b072..50dead0732 100644--- a/saleor/graphql/core/tests/test_view.py+++ b/saleor/graphql/core/tests/test_view.py@@ -6,7 +6,6 @@ from django.test import override_settingsfrom graphql.execution.base import ExecutionResultfrom .... import __version__ as saleor_version-from ....demo.views import EXAMPLE_QUERYfrom ....graphql.utils import INTERNAL_ERROR_MESSAGEfrom ...tests.fixtures import API_PATHfrom ...tests.utils import get_graphql_content, get_graphql_content_from_response@@ -243,12 +242,6 @@ def test_unexpected_exceptions_are_logged_in_their_own_logger(]-def test_example_query(api_client, product):- response = api_client.post_graphql(EXAMPLE_QUERY)- content = get_graphql_content(response)- assert content["data"]["products"]["edges"][0]["node"]["name"] == product.name--@pytest.mark.parametrize("other_query",["me{email}", 'products(first:5,channel:"channel"){edges{node{name}}}'],diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.pyindex 9d05a281e8..b8350f9095 100644--- a/saleor/graphql/middleware.py+++ b/saleor/graphql/middleware.py@@ -1,68 +1,8 @@from django.conf import settings-from ..core.exceptions import ReadOnlyException-from .core import ResolveInfofrom .views import GraphQLView-class ReadOnlyMiddleware:- ALLOWED_MUTATIONS = [- "accountRegister",- "checkoutAddPromoCode",- "checkoutBillingAddressUpdate",- "checkoutComplete",- "checkoutCreate",- "checkoutCustomerAttach",- "checkoutCustomerDetach",- "checkoutDeliveryMethodUpdate",- "checkoutEmailUpdate",- "checkoutLinesDelete",- "checkoutLinesAdd",- "checkoutLinesUpdate",- "checkoutRemovePromoCode",- "checkoutPaymentCreate",- "checkoutShippingAddressUpdate",- "checkoutShippingMethodUpdate",- "tokenCreate",- "tokenVerify",- "tokenRefresh",- "paymentGatewayInitialize",- "transactionInitialize",- "transactionProcess",- "transactionRequestAction",- "orderGrantRefundCreate",- "orderGrantRefundUpdate",- ]-- @staticmethod- def resolve(next_, root, info: ResolveInfo, **kwargs):- operation = info.operation.operation- if operation != "mutation":- return next_(root, info, **kwargs)-- # Bypass users authenticated with ROOT_EMAIL- request = info.context- user = request.user- if user:- user_email = user.email- root_email = getattr(settings, "ROOT_EMAIL", None)- if root_email and user_email == root_email:- return next_(root, info, **kwargs)-- # Bypass authenticated app as to create an app, root user is required- if request.app:- return next_(root, info, **kwargs)-- for selection in info.operation.selection_set.selections:- selection_name = str(selection.name.value)- blocked = selection_name not in ReadOnlyMiddleware.ALLOWED_MUTATIONS- if blocked:- raise ReadOnlyException(- "Be aware admin pirate! API runs in read-only mode!"- )- return next_(root, info, **kwargs)--def process_view(self, request, view_func, *args):if hasattr(view_func, "view_class") and issubclass(view_func.view_class, GraphQLViewdiff --git a/saleor/graphql/tests/test_middleware.py b/saleor/graphql/tests/test_middleware.pyindex af0dd4ec0c..b914cd2bd7 100644--- a/saleor/graphql/tests/test_middleware.py+++ b/saleor/graphql/tests/test_middleware.py@@ -1,46 +1,6 @@import pytestfrom django.test import override_settings-from ...core.exceptions import ReadOnlyException-from .utils import get_graphql_content---@override_settings(GRAPHQL_MIDDLEWARE=["saleor.graphql.middleware.ReadOnlyMiddleware"])-def test_read_only_middleware_blocked_mutation(staff_api_client):- mutation = """- mutation updateMetadata($id: ID!, $input: [MetadataInput!]!) {- updateMetadata(id: $id, input: $input) {- errors {- code- }- }- }- """- response = staff_api_client.post_graphql(- mutation, {"id": "anything", "input": [{"key": "key", "value": "value"}]}- )- content = get_graphql_content(response, ignore_errors=True)- assert (- content["errors"][0]["extensions"]["exception"]["code"]- == ReadOnlyException.__name__- )---@override_settings(GRAPHQL_MIDDLEWARE=["saleor.graphql.middleware.ReadOnlyMiddleware"])-def test_read_only_middleware_allowed_mutation(staff_api_client, customer_user):- mutation = """- mutation tokenCreate($email: String!, $password: String!){- tokenCreate(email: $email, password: $password) {- token- }- }- """- response = staff_api_client.post_graphql(- mutation, {"email": customer_user.email, "password": customer_user._password}- )- content = get_graphql_content(response)- assert content["data"]["tokenCreate"]["token"]-@override_settings(GRAPHQL_MIDDLEWARE=["saleor.graphql.middleware.NonExisting"])def test_middleware_invalid_name(api_client):diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.pyindex 0a57031da9..4fde60f4bb 100644--- a/saleor/graphql/utils/__init__.py+++ b/saleor/graphql/utils/__init__.py@@ -20,7 +20,6 @@ from ...app.models import Appfrom ...core.exceptions import (CircularSubscriptionSyncEvent,PermissionDenied,- ReadOnlyException,)from ..core.enums import PermissionEnumfrom ..core.types import TYPES_WITH_DOUBLE_ID_AVAILABLE, Permission@@ -48,7 +47,6 @@ ALLOWED_ERRORS = [GraphQLError,InvalidTokenError,PermissionDenied,- ReadOnlyException,ValidationError,QueryCostError,]diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 9c1e124b1e..d29ad9507b 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -20,7 +20,7 @@ from jwt.exceptions import PyJWTErrorfrom requests_hardened.ip_filter import InvalidIPAddressfrom .. import __version__ as saleor_version-from ..core.exceptions import PermissionDenied, ReadOnlyException+from ..core.exceptions import PermissionDeniedfrom ..core.utils import is_valid_ipv4, is_valid_ipv6from ..webhook import observabilityfrom .api import API_PATH, schema@@ -63,7 +63,6 @@ class GraphQLView(View):HANDLED_EXCEPTIONS = (GraphQLError,PyJWTError,- ReadOnlyException,PermissionDenied,InvalidIPAddress,)