Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move some logic from graphql middlewares to context setup (#8947)
Rafał Pitońf76b9d6bff05
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 62e9d0a232..44e43a1a13 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -1,3 +1,6 @@+from django.urls import reverse+from django.utils.functional import SimpleLazyObject+from ..graphql.notifications.schema import ExternalNotificationMutationsfrom .account.schema import AccountMutations, AccountQueriesfrom .app.schema import AppMutations, AppQueries@@ -24,6 +27,8 @@ from .translations.schema import TranslationQueriesfrom .warehouse.schema import StockQueries, WarehouseMutations, WarehouseQueriesfrom .webhook.schema import WebhookMutations, WebhookQueries+API_PATH = SimpleLazyObject(lambda: reverse("api"))+class Query(AccountQueries,diff --git a/saleor/graphql/context.py b/saleor/graphql/context.pynew file mode 100644index 0000000000..3ecae3b174--- /dev/null+++ b/saleor/graphql/context.py@@ -0,0 +1,48 @@+from typing import Optional++from django.contrib.auth import authenticate+from django.contrib.auth.models import AnonymousUser+from django.db.models import Exists, OuterRef+from django.utils.functional import SimpleLazyObject++from ..app.models import App, AppToken+from ..core.auth import get_token_from_request+from .api import API_PATH+++def get_context_value(request):+ set_app_on_context(request)+ set_auth_on_context(request)+ return request+++def get_app(auth_token) -> Optional[App]:+ tokens = AppToken.objects.filter(auth_token=auth_token).values("pk")+ return App.objects.filter(+ Exists(tokens.filter(app_id=OuterRef("pk"))), is_active=True+ ).first()+++def set_app_on_context(request):+ if request.path == API_PATH and not hasattr(request, "app"):+ request.app = None+ auth_token = get_token_from_request(request)+ if auth_token and len(auth_token) == 30:+ request.app = SimpleLazyObject(lambda: get_app(auth_token))+++def get_user(request):+ if not hasattr(request, "_cached_user"):+ request._cached_user = authenticate(request=request)+ return request._cached_user+++def set_auth_on_context(request):+ if hasattr(request, "app") and request.app:+ request.user = AnonymousUser()+ return request++ def user():+ return get_user(request) or AnonymousUser()++ request.user = SimpleLazyObject(lambda: user())diff --git a/saleor/graphql/core/tests/test_middleware.py b/saleor/graphql/core/tests/test_context.pysimilarity index 72%rename from saleor/graphql/core/tests/test_middleware.pyrename to saleor/graphql/core/tests/test_context.pyindex 6eac3532a7..5e35572872 100644--- a/saleor/graphql/core/tests/test_middleware.py+++ b/saleor/graphql/core/tests/test_context.py@@ -1,8 +1,6 @@-from unittest.mock import Mock-from django.urls import reverse-from ...middleware import app_middleware+from ...context import set_app_on_contextdef test_app_middleware_accepts_app_requests(app, rf):@@ -13,7 +11,7 @@ def test_app_middleware_accepts_app_requests(app, rf):request.META = {"HTTP_AUTHORIZATION": f"Bearer {token}"}# when- app_middleware(lambda root, info: info.context, Mock(), Mock(context=request))+ set_app_on_context(request)# thenassert request.app == app@@ -26,7 +24,7 @@ def test_app_middleware_accepts_saleors_header(app, rf):request.META = {"HTTP_AUTHORIZATION_BEARER": f"{token}"}# when- app_middleware(lambda root, info: info.context, Mock(), Mock(context=request))+ set_app_on_context(request)# thenassert request.app == app@@ -38,7 +36,7 @@ def test_app_middleware_skips_when_token_length_is_different_than_30(app, rf):request.META = {"HTTP_AUTHORIZATION_BEARER": "a" * 31}# when- app_middleware(lambda root, info: info.context, Mock(), Mock(context=request))+ set_app_on_context(request)# thenassert not request.appdiff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.pyindex 832392dee3..5b498e889d 100644--- a/saleor/graphql/middleware.py+++ b/saleor/graphql/middleware.py@@ -1,55 +1,7 @@-from typing import Optional-from django.conf import settings-from django.contrib.auth import authenticate-from django.contrib.auth.models import AnonymousUser-from django.db.models import Exists, OuterRef-from django.utils.functional import SimpleLazyObject-from ..app.models import App, AppToken-from ..core.auth import get_token_from_requestfrom ..core.exceptions import ReadOnlyException-from .views import API_PATH, GraphQLView---def get_user(request):- if not hasattr(request, "_cached_user"):- request._cached_user = authenticate(request=request)- return request._cached_user---class JWTMiddleware:- def resolve(self, next, root, info, **kwargs):- request = info.context-- if hasattr(request, "app") and request.app:- request.user = AnonymousUser()- return next(root, info, **kwargs)-- def user():- return get_user(request) or AnonymousUser()-- request.user = SimpleLazyObject(lambda: user())- return next(root, info, **kwargs)---def get_app(auth_token) -> Optional[App]:- tokens = AppToken.objects.filter(auth_token=auth_token).values("pk")- return App.objects.filter(- Exists(tokens.filter(app_id=OuterRef("pk"))), is_active=True- ).first()---def app_middleware(next, root, info, **kwargs):- request = info.context-- if request.path == API_PATH:- if not hasattr(request, "app"):- request.app = None- auth_token = get_token_from_request(request)- if auth_token and len(auth_token) == 30:- request.app = SimpleLazyObject(lambda: get_app(auth_token))- return next(root, info, **kwargs)+from .views import GraphQLViewclass ReadOnlyMiddleware:diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 085ee189d0..277651d62a 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -13,8 +13,6 @@ from django.db import connectionfrom django.db.backends.postgresql.base import DatabaseWrapperfrom django.http import HttpRequest, HttpResponseNotAllowed, JsonResponsefrom django.shortcuts import render-from django.urls import reverse-from django.utils.functional import SimpleLazyObjectfrom django.views.generic import Viewfrom graphene_django.settings import graphene_settingsfrom graphene_django.views import instantiate_middleware@@ -27,12 +25,12 @@ from jwt.exceptions import PyJWTErrorfrom .. import __version__ as saleor_versionfrom ..core.exceptions import PermissionDenied, ReadOnlyExceptionfrom ..core.utils import is_valid_ipv4, is_valid_ipv6-from .api import schema+from .api import API_PATH, schema+from .context import get_context_valuefrom .core.validators.query_cost import validate_query_costfrom .query_cost_map import COST_MAPfrom .utils import query_fingerprint-API_PATH = SimpleLazyObject(lambda: reverse("api"))INT_ERROR_MSG = "Int cannot represent non 32-bit signed integer value"unhandled_errors_logger = logging.getLogger("saleor.graphql.errors.unhandled")@@ -314,7 +312,7 @@ class GraphQLView(View):root=self.get_root_value(),variables=variables,operation_name=operation_name,- context=request,+ context=get_context_value(request),middleware=self.middleware,**extra_options,)diff --git a/saleor/settings.py b/saleor/settings.pyindex f33f5c9c9f..ee6c823773 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -548,11 +548,6 @@ def SENTRY_INIT(dsn: str, sentry_opts: dict):GRAPHENE = {"RELAY_CONNECTION_ENFORCE_FIRST_OR_LAST": True,"RELAY_CONNECTION_MAX_LIMIT": 100,- "MIDDLEWARE": [- # Those middlewares are executed from bottom to top- "saleor.graphql.middleware.JWTMiddleware",- "saleor.graphql.middleware.app_middleware",- ],}# Set GRAPHQL_QUERY_MAX_COMPLEXITY=0 in env to disable (not recommended)