Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Revert "Store app token as hashed password (#7556)" (#7607)
Iga Karbowiakca3e3b6412dc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17db18cd71..1481ea3fae 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -126,7 +126,6 @@ All notable, unreleased changes to this project will be documented in this file.- Fix performance for User type on resolvers: orders, gift cards, events - #7574 by @tomaszszymanski129- Fix failing account mutations for app - #7569 by @IKarbowiak- Modify order of auth middleware calls - #7572 by @tomaszszymanski129-- Store app token as hashed password - #7556 by @IKarbowiak### Breaking- Multichannel MVP: Multicurrency - #6242 by @fowczarek @d-wysockidiff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.pyindex 3c684f0068..36ba92e909 100644--- a/saleor/app/installation_utils.py+++ b/saleor/app/installation_utils.py@@ -3,7 +3,7 @@ from django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom ..app.validators import AppURLValidator-from .models import App, AppInstallation, AppToken+from .models import App, AppInstallationfrom .types import AppTypeREQUEST_TIMEOUT = 25@@ -53,11 +53,13 @@ def install_app(type=AppType.THIRDPARTY,)app.permissions.set(app_installation.permissions.all())- _token_obj, token = AppToken.objects.create_app_token(app=app, name="Default token")+ token = app.tokens.create(name="Default token")try:- send_app_token(target_url=manifest_data.get("tokenTargetUrl"), token=token)+ send_app_token(+ target_url=manifest_data.get("tokenTargetUrl"), token=token.auth_token+ )except requests.RequestException as e:app.delete()raise e- return app, token+ return appdiff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.pyindex d50052cd2c..dab5ae2974 100644--- a/saleor/app/management/commands/create_app.py+++ b/saleor/app/management/commands/create_app.py@@ -7,7 +7,7 @@ from django.core.management import BaseCommand, CommandErrorfrom django.core.management.base import CommandParserfrom requests.exceptions import RequestException-from ...models import App, AppToken+from ...models import Appfrom .utils import clean_permissions@@ -55,9 +55,9 @@ class Command(BaseCommand):permissions = clean_permissions(permissions)app = App.objects.create(name=name, is_active=is_active)app.permissions.set(permissions)- _token_obj, token = AppToken.objects.create_app_token(app=app)+ token_obj = app.tokens.create()data = {- "auth_token": token,+ "auth_token": token_obj.auth_token,}if target_url:self.send_app_data(target_url, data)diff --git a/saleor/app/management/commands/install_app.py b/saleor/app/management/commands/install_app.pyindex 5be14286aa..0ddaf186f4 100644--- a/saleor/app/management/commands/install_app.py+++ b/saleor/app/management/commands/install_app.py@@ -53,9 +53,10 @@ class Command(BaseCommand):app_job.permissions.set(permissions)try:- _app, token = install_app(app_job, activate)+ app = install_app(app_job, activate)except Exception as e:app_job.status = JobStatus.FAILEDapp_job.save()raise e- return json.dumps({"auth_token": token})+ token = app.tokens.first()+ return json.dumps({"auth_token": token.auth_token})diff --git a/saleor/app/migrations/0005_auto_20210629_0639.py b/saleor/app/migrations/0005_auto_20210629_0639.pydeleted file mode 100644index 23b98a185a..0000000000--- a/saleor/app/migrations/0005_auto_20210629_0639.py+++ /dev/null@@ -1,23 +0,0 @@-# Generated by Django 3.2.2 on 2021-06-29 06:39--from django.db import migrations, models---class Migration(migrations.Migration):-- dependencies = [- ("app", "0004_auto_20210308_1135"),- ]-- operations = [- migrations.AddField(- model_name="apptoken",- name="raw_auth_token_last_4_chars",- field=models.CharField(max_length=4, null=True),- ),- migrations.AlterField(- model_name="apptoken",- name="auth_token",- field=models.CharField(max_length=128, unique=True),- ),- ]diff --git a/saleor/app/migrations/0006_rewrite_auth_tokens.py b/saleor/app/migrations/0006_rewrite_auth_tokens.pydeleted file mode 100644index 2a3a2104e0..0000000000--- a/saleor/app/migrations/0006_rewrite_auth_tokens.py+++ /dev/null@@ -1,25 +0,0 @@-# Generated by Django 3.2.2 on 2021-06-29 06:49--from django.contrib.auth.hashers import make_password-from django.db import migrations---def rewrite_auth_tokens(apps, schema_editor):- AppToken = apps.get_model("app", "AppToken")- for token_inst in AppToken.objects.iterator():- token_inst.raw_auth_token_last_4_chars = token_inst.auth_token[-4:]- token_inst.auth_token = make_password(token_inst.auth_token)- token_inst.save(update_fields=["raw_auth_token_last_4_chars", "auth_token"])---class Migration(migrations.Migration):-- dependencies = [- ("app", "0005_auto_20210629_0639"),- ]-- operations = [- migrations.RunPython(- rewrite_auth_tokens, reverse_code=migrations.RunPython.noop- )- ]diff --git a/saleor/app/migrations/0007_alter_apptoken_raw_auth_token_last_4_chars.py b/saleor/app/migrations/0007_alter_apptoken_raw_auth_token_last_4_chars.pydeleted file mode 100644index 2f094b5230..0000000000--- a/saleor/app/migrations/0007_alter_apptoken_raw_auth_token_last_4_chars.py+++ /dev/null@@ -1,18 +0,0 @@-# Generated by Django 3.2.2 on 2021-06-29 07:29--from django.db import migrations, models---class Migration(migrations.Migration):-- dependencies = [- ("app", "0006_rewrite_auth_tokens"),- ]-- operations = [- migrations.AlterField(- model_name="apptoken",- name="raw_auth_token_last_4_chars",- field=models.CharField(max_length=4),- ),- ]diff --git a/saleor/app/models.py b/saleor/app/models.pyindex 2d3441a033..b104ff79ea 100644--- a/saleor/app/models.py+++ b/saleor/app/models.py@@ -1,6 +1,5 @@-from typing import Set, Tuple+from typing import Set-from django.contrib.auth.hashers import check_password, make_passwordfrom django.contrib.auth.models import Permissionfrom django.db import modelsfrom oauthlib.common import generate_token@@ -98,46 +97,10 @@ class App(ModelWithMetadata):return perm_value in self.get_permissions()-class AppTokenManager(models.Manager):- def create_app_token(self, app: App, name: str = "") -> Tuple["AppToken", str]:- """Create app token and save the value as hashed password."""- token = generate_token()- auth_token = make_password(token)- token_obj = self.create(- name=name,- app=app,- auth_token=auth_token,- raw_auth_token_last_4_chars=token[-4:],- )- return token_obj, token-- def validate_app_token(self, token: str):- """Verify provided app token."""- apps = App.objects.filter(is_active=True)- auth_tokens = self.filter(- models.Exists(apps.filter(pk=models.OuterRef("app_id")))- ).values_list("auth_token", flat=True)- return any([check_password(token, auth_token) for auth_token in auth_tokens])--class AppToken(models.Model):app = models.ForeignKey(App, on_delete=models.CASCADE, related_name="tokens")name = models.CharField(blank=True, default="", max_length=128)- auth_token = models.CharField(unique=True, max_length=128)- raw_auth_token_last_4_chars = models.CharField(max_length=4)-- objects = AppTokenManager()-- def create_auth_token(self) -> str:- """Create app token and assign the value as hashed password.-- Save last 4 token characters of raw token.- Return raw token. Required save after execution.- """- token = generate_token()- self.auth_token = make_password(token)- self.raw_auth_token_last_4_chars = token[-4:]- return token+ auth_token = models.CharField(default=generate_token, unique=True, max_length=30)class AppInstallation(Job):diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.pyindex c352badc3e..28652ab18b 100644--- a/saleor/app/tests/test_app_commands.py+++ b/saleor/app/tests/test_app_commands.py@@ -1,8 +1,7 @@-from unittest.mock import Mock+from unittest.mock import ANY, Mockimport pytestimport requests-from django.contrib.auth.hashers import check_passwordfrom django.core.management import call_commandfrom ...core import JobStatus@@ -57,18 +56,13 @@ def test_creates_app_from_manifest_sends_token(monkeypatch):call_command("install_app", manifest_url)app = App.objects.get()- auth_token = app.tokens.first().auth_token-- assert mocked_post.call_count == 1- args, kwargs = mocked_post.call_args- assert len(args) == 1- assert args[0] == "http://localhost:3000/register"- assert kwargs["headers"] == {- "Content-Type": "application/json",- "x-saleor-domain": "mirumee.com",- }- token = kwargs["json"]["auth_token"]- assert check_password(token, auth_token)+ token = app.tokens.all()[0].auth_token+ mocked_post.assert_called_once_with(+ "http://localhost:3000/register",+ headers={"Content-Type": "application/json", "x-saleor-domain": "mirumee.com"},+ json={"auth_token": token},+ timeout=ANY,+ )@pytest.mark.vcr@@ -122,12 +116,10 @@ def test_sends_data_to_target_url(monkeypatch):call_command("create_app", name, permission=permissions, target_url=target_url)app = App.objects.filter(name=name)[0]- auth_token = app.tokens.first().auth_token-- assert mocked_post.call_count == 1- args, kwargs = mocked_post.call_args- assert len(args) == 1- assert args[0] == target_url- assert kwargs["headers"] == {"x-saleor-domain": "mirumee.com"}- token = kwargs["json"]["auth_token"]- assert check_password(token, auth_token)+ token = app.tokens.all()[0].auth_token+ mocked_post.assert_called_once_with(+ target_url,+ headers={"x-saleor-domain": "mirumee.com"},+ json={"auth_token": token},+ timeout=ANY,+ )diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.pyindex cc77a7a8ec..6507f18b14 100644--- a/saleor/graphql/app/mutations.py+++ b/saleor/graphql/app/mutations.py@@ -68,12 +68,11 @@ class AppTokenCreate(ModelMutation):instance = cls.get_instance(info, **data)cleaned_input = cls.clean_input(info, instance, input_data)instance = cls.construct_instance(instance, cleaned_input)- token = instance.create_auth_token()cls.clean_instance(info, instance)cls.save(info, instance, cleaned_input)cls._save_m2m(info, instance, cleaned_input)response = cls.success_response(instance)- response.auth_token = token+ response.auth_token = instance.auth_tokenreturn response@classmethod@@ -131,8 +130,10 @@ class AppTokenVerify(BaseMutation):@classmethoddef perform_mutation(cls, root, info, **data):token = data.get("token")- valid = models.AppToken.objects.validate_app_token(token)- return AppTokenVerify(valid=valid)+ app_token = models.AppToken.objects.filter(+ auth_token=token, app__is_active=True+ ).first()+ return AppTokenVerify(valid=bool(app_token))class AppCreate(ModelMutation):@@ -168,13 +169,15 @@ class AppCreate(ModelMutation):ensure_can_manage_permissions(requestor, permissions)return cleaned_input+ @classmethod+ def save(cls, info, instance, cleaned_input):+ instance.save()+ instance.tokens.create(name="Default")+@classmethoddef success_response(cls, instance):response = super().success_response(instance)- _token_inst, token = models.AppToken.objects.create_app_token(- app=instance, name="Default"- )- response.auth_token = token+ response.auth_token = instance.tokens.get().auth_tokenreturn responsediff --git a/saleor/graphql/app/tests/mutations/test_app_create.py b/saleor/graphql/app/tests/mutations/test_app_create.pyindex eced514a4e..e5495469de 100644--- a/saleor/graphql/app/tests/mutations/test_app_create.py+++ b/saleor/graphql/app/tests/mutations/test_app_create.py@@ -1,5 +1,3 @@-from django.contrib.auth.hashers import check_password-from .....app.error_codes import AppErrorCodefrom .....app.models import Appfrom ....core.enums import PermissionEnum@@ -59,7 +57,7 @@ def test_app_create_mutation(assert app_data["isActive"] == app.is_activeassert app_data["name"] == app.nameassert list(app.permissions.all()) == [permission_manage_products]- assert check_password(default_token, app.tokens.get().auth_token)+ assert default_token == app.tokens.get().auth_tokendef test_app_create_mutation_for_app(@@ -84,7 +82,7 @@ def test_app_create_mutation_for_app(assert app_data["isActive"] == app.is_activeassert app_data["name"] == app.nameassert list(app.permissions.all()) == [permission_manage_products]- assert check_password(default_token, app.tokens.get().auth_token)+ assert default_token == app.tokens.get().auth_tokendef test_app_create_mutation_out_of_scope_permissions(@@ -139,7 +137,7 @@ def test_app_create_mutation_superuser_can_create_app_with_any_perms(assert app_data["isActive"] == app.is_activeassert app_data["name"] == app.nameassert list(app.permissions.all()) == [permission_manage_products]- assert check_password(default_token, app.tokens.get().auth_token)+ assert default_token == app.tokens.get().auth_tokendef test_app_create_mutation_for_app_out_of_scope_permissions(diff --git a/saleor/graphql/app/tests/mutations/test_app_token_create.py b/saleor/graphql/app/tests/mutations/test_app_token_create.pyindex ea593d2e12..e699d5db63 100644--- a/saleor/graphql/app/tests/mutations/test_app_token_create.py+++ b/saleor/graphql/app/tests/mutations/test_app_token_create.py@@ -1,5 +1,4 @@import graphene-from django.contrib.auth.hashers import check_passwordfrom .....app.error_codes import AppErrorCodefrom .....app.models import App@@ -42,9 +41,9 @@ def test_app_token_create(token_data = content["data"]["appTokenCreate"]["appToken"]auth_token_data = content["data"]["appTokenCreate"]["authToken"]auth_token = app.tokens.get().auth_token- assert check_password(auth_token_data, auth_token)+ assert auth_token_data == auth_token- assert token_data["authToken"] == auth_token_data[-4:]+ assert token_data["authToken"] == auth_token[-4:]assert token_data["name"] == "Default token"@@ -71,9 +70,9 @@ def test_app_token_create_for_app(token_data = content["data"]["appTokenCreate"]["appToken"]auth_token_data = content["data"]["appTokenCreate"]["authToken"]auth_token = app.tokens.get().auth_token- assert check_password(auth_token_data, auth_token)+ assert auth_token_data == auth_token- assert token_data["authToken"] == auth_token_data[-4:]+ assert token_data["authToken"] == auth_token[-4:]assert token_data["name"] == "Default token"@@ -125,9 +124,9 @@ def test_app_token_create_superuser_can_create_token_for_any_app(token_data = content["data"]["appTokenCreate"]["appToken"]auth_token_data = content["data"]["appTokenCreate"]["authToken"]auth_token = app.tokens.get().auth_token- assert check_password(auth_token_data, auth_token)+ assert auth_token_data == auth_token- assert token_data["authToken"] == auth_token_data[-4:]+ assert token_data["authToken"] == auth_token[-4:]assert token_data["name"] == "Default token"diff --git a/saleor/graphql/app/tests/mutations/test_app_token_delete.py b/saleor/graphql/app/tests/mutations/test_app_token_delete.pyindex 33ae1e282d..17a3a413fd 100644--- a/saleor/graphql/app/tests/mutations/test_app_token_delete.py+++ b/saleor/graphql/app/tests/mutations/test_app_token_delete.py@@ -25,12 +25,11 @@ def test_app_token_delete(permission_manage_apps,staff_api_client,staff_user,- app_with_token,+ app,permission_manage_products,):query = APP_TOKEN_DELETE_MUTATION- app = app_with_tokentoken = app.tokens.get()staff_user.user_permissions.add(permission_manage_products)app.permissions.add(permission_manage_products)@@ -65,10 +64,10 @@ def test_app_token_delete_for_app(assert not AppToken.objects.filter(id=token.id).first()-def test_app_token_delete_no_permissions(staff_api_client, staff_user, app_with_token):+def test_app_token_delete_no_permissions(staff_api_client, staff_user, app):query = APP_TOKEN_DELETE_MUTATION- token = app_with_token.tokens.get()+ token = app.tokens.get()id = graphene.Node.to_global_id("AppToken", token.id)variables = {"id": id}@@ -81,12 +80,11 @@ def test_app_token_delete_out_of_scope_app(permission_manage_apps,staff_api_client,staff_user,- app_with_token,+ app,permission_manage_products,):"""Ensure user can't delete app token with wider scope of permissions."""query = APP_TOKEN_DELETE_MUTATION- app = app_with_tokentoken = app.tokens.get()app.permissions.add(permission_manage_products)id = graphene.Node.to_global_id("AppToken", token.id)@@ -113,12 +111,11 @@ def test_app_token_delete_out_of_scope_app(def test_app_token_delete_superuser_can_delete_token_for_any_app(permission_manage_apps,superuser_api_client,- app_with_token,+ app,permission_manage_products,):"""Ensure superuser can delete app token for app with any scope of permissions."""query = APP_TOKEN_DELETE_MUTATION- app = app_with_tokentoken = app.tokens.get()app.permissions.add(permission_manage_products)id = graphene.Node.to_global_id("AppToken", token.id)diff --git a/saleor/graphql/app/tests/mutations/test_app_token_verify.py b/saleor/graphql/app/tests/mutations/test_app_token_verify.pyindex bed41d253f..6d70fc2913 100644--- a/saleor/graphql/app/tests/mutations/test_app_token_verify.py+++ b/saleor/graphql/app/tests/mutations/test_app_token_verify.py@@ -1,4 +1,3 @@-from .....app.models import AppTokenfrom ....tests.utils import get_graphql_contentAPP_TOKEN_VERIFY_MUTATION = """@@ -11,7 +10,7 @@ mutation AppTokenVerify($token: String!){def test_app_token_verify_valid_token(app, api_client):- _token_obj, token = AppToken.objects.create_app_token(app=app)+ token = app.tokens.first().auth_tokenquery = APP_TOKEN_VERIFY_MUTATIONvariables = {"token": token}@@ -20,21 +19,8 @@ def test_app_token_verify_valid_token(app, api_client):assert content["data"]["appTokenVerify"]["valid"]-def test_app_token_verify_valid_token_and_inactive_app(app, api_client):- app.is_active = False- app.save(update_fields=["is_active"])-- _token_obj, token = AppToken.objects.create_app_token(app=app)- query = APP_TOKEN_VERIFY_MUTATION-- variables = {"token": token}- response = api_client.post_graphql(query, variables=variables)- content = get_graphql_content(response)- assert not content["data"]["appTokenVerify"]["valid"]--def test_app_token_verify_invalid_token(app, api_client):- _token_obj, token = AppToken.objects.create_app_token(app=app)+ token = app.tokens.first().auth_tokentoken += "incorrect"query = APP_TOKEN_VERIFY_MUTATIONdiff --git a/saleor/graphql/app/tests/mutations/test_app_update.py b/saleor/graphql/app/tests/mutations/test_app_update.pyindex fc4fa911a3..7b0827ae1c 100644--- a/saleor/graphql/app/tests/mutations/test_app_update.py+++ b/saleor/graphql/app/tests/mutations/test_app_update.py@@ -33,7 +33,7 @@ mutation AppUpdate($id: ID!, $permissions: [PermissionEnum]){def test_app_update_mutation(- app_with_token,+ app,permission_manage_apps,permission_manage_products,permission_manage_users,@@ -41,7 +41,6 @@ def test_app_update_mutation(staff_user,):query = APP_UPDATE_MUTATION- app = app_with_tokenstaff_user.user_permissions.add(permission_manage_products, permission_manage_users)id = graphene.Node.to_global_id("App", app.id)@@ -152,7 +151,7 @@ def test_app_update_mutation_out_of_scope_permissions(def test_app_update_mutation_superuser_can_add_any_permissions_to_app(- app_with_token,+ app,permission_manage_apps,permission_manage_products,permission_manage_users,@@ -160,7 +159,6 @@ def test_app_update_mutation_superuser_can_add_any_permissions_to_app():"""Ensure superuser can add any permissions to app."""query = APP_UPDATE_MUTATION- app = app_with_tokenid = graphene.Node.to_global_id("App", app.id)variables = {@@ -228,7 +226,7 @@ def test_app_update_mutation_for_app_out_of_scope_permissions(def test_app_update_mutation_out_of_scope_app(- app_with_token,+ app,permission_manage_apps,permission_manage_products,permission_manage_orders,@@ -238,7 +236,6 @@ def test_app_update_mutation_out_of_scope_app():"""Ensure user cannot manage app with wider permission scope."""query = APP_UPDATE_MUTATION- app = app_with_tokenstaff_user.user_permissions.add(permission_manage_apps,permission_manage_products,@@ -268,7 +265,7 @@ def test_app_update_mutation_out_of_scope_app(def test_app_update_mutation_superuser_can_update_any_app(- app_with_token,+ app,permission_manage_apps,permission_manage_products,permission_manage_orders,@@ -277,7 +274,6 @@ def test_app_update_mutation_superuser_can_update_any_app():"""Ensure superuser can manage any app."""query = APP_UPDATE_MUTATION- app = app_with_tokenapp.permissions.add(permission_manage_orders)id = graphene.Node.to_global_id("App", app.id)@@ -344,9 +340,9 @@ def test_app_update_mutation_for_app_out_of_scope_app(assert error["code"] == AppErrorCode.OUT_OF_SCOPE_APP.name-def test_app_update_no_permission(app_with_token, staff_api_client, staff_user):+def test_app_update_no_permission(app, staff_api_client, staff_user):query = APP_UPDATE_MUTATION- id = graphene.Node.to_global_id("App", app_with_token.id)+ id = graphene.Node.to_global_id("App", app.id)variables = {"id": id,"permissions": [PermissionEnum.MANAGE_PRODUCTS.name],diff --git a/saleor/graphql/app/tests/queries/test_app.py b/saleor/graphql/app/tests/queries/test_app.pyindex b5902024cf..f4841265f2 100644--- a/saleor/graphql/app/tests/queries/test_app.py+++ b/saleor/graphql/app/tests/queries/test_app.py@@ -42,11 +42,11 @@ def test_app_query(staff_api_client,permission_manage_apps,permission_manage_staff,- app_with_token,+ app,external_app,webhook,):- app = app_with_token if app_type == "custom" else external_app+ app = app if app_type == "custom" else external_appapp.permissions.add(permission_manage_staff)webhook = webhookdiff --git a/saleor/graphql/app/tests/queries/test_apps.py b/saleor/graphql/app/tests/queries/test_apps.pyindex ba448f3b3c..ccbab61c36 100644--- a/saleor/graphql/app/tests/queries/test_apps.py+++ b/saleor/graphql/app/tests/queries/test_apps.py@@ -53,7 +53,7 @@ def test_apps_query(staff_api_client,permission_manage_apps,permission_manage_orders,- app_with_token,+ app,external_app,app_filter,count,@@ -62,11 +62,7 @@ def test_apps_query(external_app.save()webhooks = Webhook.objects.bulk_create([- Webhook(- app=app_with_token,- name="first",- target_url="http://www.example.com/test",- ),+ Webhook(app=app, name="first", target_url="http://www.example.com/test"),Webhook(app=external_app, name="second", target_url="http://www.exa.com/s"),])diff --git a/saleor/graphql/app/types.py b/saleor/graphql/app/types.pyindex cad7cbe9f2..57078191f6 100644--- a/saleor/graphql/app/types.py+++ b/saleor/graphql/app/types.py@@ -45,7 +45,7 @@ class AppToken(CountableDjangoObjectType):@staticmethoddef resolve_auth_token(root: models.AppToken, _info, **_kwargs):- return root.raw_auth_token_last_4_chars+ return root.auth_token[-4:]@key(fields="id")diff --git a/saleor/graphql/core/tests/test_middleware.py b/saleor/graphql/core/tests/test_middleware.pyindex f9d2ec299b..043b4576fa 100644--- a/saleor/graphql/core/tests/test_middleware.py+++ b/saleor/graphql/core/tests/test_middleware.py@@ -2,7 +2,6 @@ from unittest.mock import Mockfrom django.urls import reverse-from ....app.models import AppTokenfrom ...middleware import app_middleware@@ -10,7 +9,7 @@ def test_app_middleware_accepts_api_requests(app, rf):# Retrieve sample request objectrequest = rf.get(reverse("api"))- _token_inst, token = AppToken.objects.create_app_token(app=app)+ token = app.tokens.first().auth_tokenrequest.META = {"HTTP_AUTHORIZATION": f"Bearer {token}"}app_middleware(lambda root, info: info.context, Mock(), Mock(context=request))diff --git a/saleor/graphql/csv/tests/queries/test_export_files.py b/saleor/graphql/csv/tests/queries/test_export_files.pyindex b12aa36504..0d7ed73ec4 100644--- a/saleor/graphql/csv/tests/queries/test_export_files.py+++ b/saleor/graphql/csv/tests/queries/test_export_files.py@@ -5,7 +5,7 @@ import pytestfrom django.utils import timezonefrom .....account.models import User-from .....app.models import App, AppToken+from .....app.models import Appfrom .....core import JobStatusfrom .....csv.models import ExportFilefrom ....tests.utils import get_graphql_content@@ -184,7 +184,7 @@ def test_filter_export_files_by_app(app,):app2 = App.objects.create(name="Another app", is_active=True)- AppToken.objects.create_app_token(app=app2, name="Default")+ app2.tokens.create(name="Default")export_file_list[0].user = Noneexport_file_list[0].app = appdiff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.pyindex 0feca667bd..a971f3b496 100644--- a/saleor/graphql/middleware.py+++ b/saleor/graphql/middleware.py@@ -2,7 +2,6 @@ from typing import Optionalfrom django.conf import settingsfrom django.contrib.auth import authenticate-from django.contrib.auth.hashers import check_passwordfrom django.contrib.auth.models import AnonymousUserfrom django.db.models import Exists, OuterReffrom django.utils.functional import SimpleLazyObject@@ -29,13 +28,11 @@ class JWTMiddleware:return next(root, info, **kwargs)-def get_app(token) -> Optional[App]:- apps = App.objects.filter(is_active=True)- app_tokens = AppToken.objects.filter(Exists(apps.filter(pk=OuterRef("app_id"))))- for app_token in app_tokens:- if check_password(token, app_token.auth_token):- return app_token.app- return None+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):diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.pyindex c01cf91f22..641e5f2a84 100644--- a/saleor/graphql/tests/fixtures.py+++ b/saleor/graphql/tests/fixtures.py@@ -10,7 +10,6 @@ from django.shortcuts import reversefrom django.test.client import MULTIPART_CONTENT, Clientfrom ...account.models import User-from ...app.models import AppTokenfrom ...core.jwt import create_access_tokenfrom ...plugins.manager import get_plugins_managerfrom ...tests.utils import flush_post_commit_hooks@@ -33,10 +32,13 @@ class ApiClient(Client):self._user = Noneself.token = Noneself.user = user- self.app_token = kwargs.pop("app_token", None)+ self.app_token = Noneself.app = appif not user.is_anonymous:self.token = create_access_token(user)+ elif app:+ token = app.tokens.first()+ self.app_token = token.auth_token if token else Nonesuper().__init__(*args, **kwargs)def _base_environ(self, **request):@@ -118,8 +120,7 @@ class ApiClient(Client):@pytest.fixturedef app_api_client(app):- _token_inst, token = AppToken.objects.create_app_token(app=app, name="Default")- return ApiClient(app=app, app_token=token)+ return ApiClient(app=app)@pytest.fixturediff --git a/saleor/graphql/tests/test_middleware.py b/saleor/graphql/tests/test_middleware.pydeleted file mode 100644index 737ff4c6d0..0000000000--- a/saleor/graphql/tests/test_middleware.py+++ /dev/null@@ -1,35 +0,0 @@-from ...app.models import AppToken-from ..middleware import get_app---def test_get_app(app):- # given- _token_inst, token = AppToken.objects.create_app_token(app=app, name="test")-- # when- returned_app = get_app(token)-- # then- assert returned_app.id == app.id---def test_get_app_not_active(app):- # given- app.is_active = False- app.save(update_fields=["is_active"])-- _token_inst, token = AppToken.objects.create_app_token(app=app, name="test")-- # when- returned_app = get_app(token)-- # then- assert returned_app is None---def test_get_app_no_app_found():- # when- returned_app = get_app("test")-- # then- assert returned_app is Nonediff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.pyindex db2efaae98..ca063f0a86 100644--- a/saleor/plugins/webhook/tests/test_payment_webhook.py+++ b/saleor/plugins/webhook/tests/test_payment_webhook.py@@ -3,7 +3,7 @@ from unittest import mockimport pytest-from ....app.models import App, AppToken+from ....app.models import Appfrom ....payment import PaymentError, TransactionKindfrom ....payment.utils import create_payment_informationfrom ....webhook.event_types import WebhookEventType@@ -126,7 +126,7 @@ def test_get_payment_gateways():# Create second app to test results from multiple apps.app_2 = App.objects.create(name="Payment App 2", is_active=True)- AppToken.objects.create_app_token(app=app_2, name="Default")+ app_2.tokens.create(name="Default")app_2.permissions.add(permission_manage_payments)webhook = Webhook.objects.create(name="payment-webhook-2",diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 332210b20b..dc4dab7c70 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -26,7 +26,7 @@ from PIL import Imagefrom prices import Money, TaxedMoney, fixed_discountfrom ..account.models import Address, StaffNotificationRecipient, User-from ..app.models import App, AppInstallation, AppToken+from ..app.models import App, AppInstallationfrom ..app.types import AppTypefrom ..attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ..attribute.models import (@@ -3689,19 +3689,15 @@ def other_description_json():@pytest.fixturedef app(db):- return App.objects.create(name="Sample app objects", is_active=True)---def app_with_token(app):- AppToken.objects.create_app_token(app=app, name="Default")+ app = App.objects.create(name="Sample app objects", is_active=True)+ app.tokens.create(name="Default")return app@pytest.fixturedef payment_app(db, permission_manage_payments):app = App.objects.create(name="Payment App", is_active=True)- AppToken.objects.create_app_token(app=app, name="Default")+ app.tokens.create(name="Default")app.permissions.add(permission_manage_payments)webhook = Webhook.objects.create(@@ -3733,7 +3729,7 @@ def external_app(db):configuration_url="http://www.example.com/app-configuration/",app_url="http://www.example.com/app/",)- AppToken.objects.create_app_token(app=app, name="Default")+ app.tokens.create(name="Default")return app