Skip to content

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

Store app token as hashed password (#7556)

Iga Karbowiak6afcca239845
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1481ea3fae..17db18cd71 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -126,6 +126,7 @@ 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-wysocki
diff --git a/saleor/app/installation_utils.py b/saleor/app/installation_utils.py
index 36ba92e909..3c684f0068 100644
--- a/saleor/app/installation_utils.py
+++ b/saleor/app/installation_utils.py
@@ -3,7 +3,7 @@ from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from ..app.validators import AppURLValidator
-from .models import App, AppInstallation
+from .models import App, AppInstallation, AppToken
from .types import AppType
REQUEST_TIMEOUT = 25
@@ -53,13 +53,11 @@ def install_app(
type=AppType.THIRDPARTY,
)
app.permissions.set(app_installation.permissions.all())
- token = app.tokens.create(name="Default token")
+ _token_obj, token = AppToken.objects.create_app_token(app=app, name="Default token")
try:
- send_app_token(
- target_url=manifest_data.get("tokenTargetUrl"), token=token.auth_token
- )
+ send_app_token(target_url=manifest_data.get("tokenTargetUrl"), token=token)
except requests.RequestException as e:
app.delete()
raise e
- return app
+ return app, token
diff --git a/saleor/app/management/commands/create_app.py b/saleor/app/management/commands/create_app.py
index dab5ae2974..d50052cd2c 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, CommandError
from django.core.management.base import CommandParser
from requests.exceptions import RequestException
-from ...models import App
+from ...models import App, AppToken
from .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 = app.tokens.create()
+ _token_obj, token = AppToken.objects.create_app_token(app=app)
data = {
- "auth_token": token_obj.auth_token,
+ "auth_token": 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.py
index 0ddaf186f4..5be14286aa 100644
--- a/saleor/app/management/commands/install_app.py
+++ b/saleor/app/management/commands/install_app.py
@@ -53,10 +53,9 @@ class Command(BaseCommand):
app_job.permissions.set(permissions)
try:
- app = install_app(app_job, activate)
+ _app, token = install_app(app_job, activate)
except Exception as e:
app_job.status = JobStatus.FAILED
app_job.save()
raise e
- token = app.tokens.first()
- return json.dumps({"auth_token": token.auth_token})
+ return json.dumps({"auth_token": token})
diff --git a/saleor/app/migrations/0005_auto_20210629_0639.py b/saleor/app/migrations/0005_auto_20210629_0639.py
new file mode 100644
index 0000000000..23b98a185a
--- /dev/null
+++ b/saleor/app/migrations/0005_auto_20210629_0639.py
@@ -0,0 +1,23 @@
+# 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.py
new file mode 100644
index 0000000000..2a3a2104e0
--- /dev/null
+++ b/saleor/app/migrations/0006_rewrite_auth_tokens.py
@@ -0,0 +1,25 @@
+# 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.py
new file mode 100644
index 0000000000..2f094b5230
--- /dev/null
+++ b/saleor/app/migrations/0007_alter_apptoken_raw_auth_token_last_4_chars.py
@@ -0,0 +1,18 @@
+# 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.py
index b104ff79ea..2d3441a033 100644
--- a/saleor/app/models.py
+++ b/saleor/app/models.py
@@ -1,5 +1,6 @@
-from typing import Set
+from typing import Set, Tuple
+from django.contrib.auth.hashers import check_password, make_password
from django.contrib.auth.models import Permission
from django.db import models
from oauthlib.common import generate_token
@@ -97,10 +98,46 @@ 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(default=generate_token, unique=True, max_length=30)
+ 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
class AppInstallation(Job):
diff --git a/saleor/app/tests/test_app_commands.py b/saleor/app/tests/test_app_commands.py
index 28652ab18b..c352badc3e 100644
--- a/saleor/app/tests/test_app_commands.py
+++ b/saleor/app/tests/test_app_commands.py
@@ -1,7 +1,8 @@
-from unittest.mock import ANY, Mock
+from unittest.mock import Mock
import pytest
import requests
+from django.contrib.auth.hashers import check_password
from django.core.management import call_command
from ...core import JobStatus
@@ -56,13 +57,18 @@ def test_creates_app_from_manifest_sends_token(monkeypatch):
call_command("install_app", manifest_url)
app = App.objects.get()
- 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,
- )
+ 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)
@pytest.mark.vcr
@@ -116,10 +122,12 @@ 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]
- 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,
- )
+ 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)
diff --git a/saleor/graphql/app/mutations.py b/saleor/graphql/app/mutations.py
index 6507f18b14..cc77a7a8ec 100644
--- a/saleor/graphql/app/mutations.py
+++ b/saleor/graphql/app/mutations.py
@@ -68,11 +68,12 @@ 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 = instance.auth_token
+ response.auth_token = token
return response
@classmethod
@@ -130,10 +131,8 @@ class AppTokenVerify(BaseMutation):
@classmethod
def perform_mutation(cls, root, info, **data):
token = data.get("token")
- app_token = models.AppToken.objects.filter(
- auth_token=token, app__is_active=True
- ).first()
- return AppTokenVerify(valid=bool(app_token))
+ valid = models.AppToken.objects.validate_app_token(token)
+ return AppTokenVerify(valid=valid)
class AppCreate(ModelMutation):
@@ -169,15 +168,13 @@ 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")
-
@classmethod
def success_response(cls, instance):
response = super().success_response(instance)
- response.auth_token = instance.tokens.get().auth_token
+ _token_inst, token = models.AppToken.objects.create_app_token(
+ app=instance, name="Default"
+ )
+ response.auth_token = token
return response
diff --git a/saleor/graphql/app/tests/mutations/test_app_create.py b/saleor/graphql/app/tests/mutations/test_app_create.py
index e5495469de..eced514a4e 100644
--- a/saleor/graphql/app/tests/mutations/test_app_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_create.py
@@ -1,3 +1,5 @@
+from django.contrib.auth.hashers import check_password
+
from .....app.error_codes import AppErrorCode
from .....app.models import App
from ....core.enums import PermissionEnum
@@ -57,7 +59,7 @@ def test_app_create_mutation(
assert app_data["isActive"] == app.is_active
assert app_data["name"] == app.name
assert list(app.permissions.all()) == [permission_manage_products]
- assert default_token == app.tokens.get().auth_token
+ assert check_password(default_token, app.tokens.get().auth_token)
def test_app_create_mutation_for_app(
@@ -82,7 +84,7 @@ def test_app_create_mutation_for_app(
assert app_data["isActive"] == app.is_active
assert app_data["name"] == app.name
assert list(app.permissions.all()) == [permission_manage_products]
- assert default_token == app.tokens.get().auth_token
+ assert check_password(default_token, app.tokens.get().auth_token)
def test_app_create_mutation_out_of_scope_permissions(
@@ -137,7 +139,7 @@ def test_app_create_mutation_superuser_can_create_app_with_any_perms(
assert app_data["isActive"] == app.is_active
assert app_data["name"] == app.name
assert list(app.permissions.all()) == [permission_manage_products]
- assert default_token == app.tokens.get().auth_token
+ assert check_password(default_token, app.tokens.get().auth_token)
def 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.py
index e699d5db63..ea593d2e12 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_create.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_create.py
@@ -1,4 +1,5 @@
import graphene
+from django.contrib.auth.hashers import check_password
from .....app.error_codes import AppErrorCode
from .....app.models import App
@@ -41,9 +42,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 auth_token_data == auth_token
+ assert check_password(auth_token_data, auth_token)
- assert token_data["authToken"] == auth_token[-4:]
+ assert token_data["authToken"] == auth_token_data[-4:]
assert token_data["name"] == "Default token"
@@ -70,9 +71,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 auth_token_data == auth_token
+ assert check_password(auth_token_data, auth_token)
- assert token_data["authToken"] == auth_token[-4:]
+ assert token_data["authToken"] == auth_token_data[-4:]
assert token_data["name"] == "Default token"
@@ -124,9 +125,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 auth_token_data == auth_token
+ assert check_password(auth_token_data, auth_token)
- assert token_data["authToken"] == auth_token[-4:]
+ assert token_data["authToken"] == auth_token_data[-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.py
index 17a3a413fd..33ae1e282d 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_delete.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_delete.py
@@ -25,11 +25,12 @@ def test_app_token_delete(
permission_manage_apps,
staff_api_client,
staff_user,
- app,
+ app_with_token,
permission_manage_products,
):
query = APP_TOKEN_DELETE_MUTATION
+ app = app_with_token
token = app.tokens.get()
staff_user.user_permissions.add(permission_manage_products)
app.permissions.add(permission_manage_products)
@@ -64,10 +65,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):
+def test_app_token_delete_no_permissions(staff_api_client, staff_user, app_with_token):
query = APP_TOKEN_DELETE_MUTATION
- token = app.tokens.get()
+ token = app_with_token.tokens.get()
id = graphene.Node.to_global_id("AppToken", token.id)
variables = {"id": id}
@@ -80,11 +81,12 @@ def test_app_token_delete_out_of_scope_app(
permission_manage_apps,
staff_api_client,
staff_user,
- app,
+ app_with_token,
permission_manage_products,
):
"""Ensure user can't delete app token with wider scope of permissions."""
query = APP_TOKEN_DELETE_MUTATION
+ app = app_with_token
token = app.tokens.get()
app.permissions.add(permission_manage_products)
id = graphene.Node.to_global_id("AppToken", token.id)
@@ -111,11 +113,12 @@ 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,
+ app_with_token,
permission_manage_products,
):
"""Ensure superuser can delete app token for app with any scope of permissions."""
query = APP_TOKEN_DELETE_MUTATION
+ app = app_with_token
token = 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.py
index 6d70fc2913..bed41d253f 100644
--- a/saleor/graphql/app/tests/mutations/test_app_token_verify.py
+++ b/saleor/graphql/app/tests/mutations/test_app_token_verify.py
@@ -1,3 +1,4 @@
+from .....app.models import AppToken
from ....tests.utils import get_graphql_content
APP_TOKEN_VERIFY_MUTATION = """
@@ -10,7 +11,7 @@ mutation AppTokenVerify($token: String!){
def test_app_token_verify_valid_token(app, api_client):
- token = app.tokens.first().auth_token
+ _token_obj, token = AppToken.objects.create_app_token(app=app)
query = APP_TOKEN_VERIFY_MUTATION
variables = {"token": token}
@@ -19,8 +20,21 @@ 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 = app.tokens.first().auth_token
+ _token_obj, token = AppToken.objects.create_app_token(app=app)
token += "incorrect"
query = APP_TOKEN_VERIFY_MUTATION
diff --git a/saleor/graphql/app/tests/mutations/test_app_update.py b/saleor/graphql/app/tests/mutations/test_app_update.py
index 7b0827ae1c..fc4fa911a3 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,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_users,
@@ -41,6 +41,7 @@ def test_app_update_mutation(
staff_user,
):
query = APP_UPDATE_MUTATION
+ app = app_with_token
staff_user.user_permissions.add(permission_manage_products, permission_manage_users)
id = graphene.Node.to_global_id("App", app.id)
@@ -151,7 +152,7 @@ def test_app_update_mutation_out_of_scope_permissions(
def test_app_update_mutation_superuser_can_add_any_permissions_to_app(
- app,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_users,
@@ -159,6 +160,7 @@ 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_token
id = graphene.Node.to_global_id("App", app.id)
variables = {
@@ -226,7 +228,7 @@ def test_app_update_mutation_for_app_out_of_scope_permissions(
def test_app_update_mutation_out_of_scope_app(
- app,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_orders,
@@ -236,6 +238,7 @@ 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_token
staff_user.user_permissions.add(
permission_manage_apps,
permission_manage_products,
@@ -265,7 +268,7 @@ def test_app_update_mutation_out_of_scope_app(
def test_app_update_mutation_superuser_can_update_any_app(
- app,
+ app_with_token,
permission_manage_apps,
permission_manage_products,
permission_manage_orders,
@@ -274,6 +277,7 @@ def test_app_update_mutation_superuser_can_update_any_app(
):
"""Ensure superuser can manage any app."""
query = APP_UPDATE_MUTATION
+ app = app_with_token
app.permissions.add(permission_manage_orders)
id = graphene.Node.to_global_id("App", app.id)
@@ -340,9 +344,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, staff_api_client, staff_user):
+def test_app_update_no_permission(app_with_token, staff_api_client, staff_user):
query = APP_UPDATE_MUTATION
- id = graphene.Node.to_global_id("App", app.id)
+ id = graphene.Node.to_global_id("App", app_with_token.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.py
index f4841265f2..b5902024cf 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,
+ app_with_token,
external_app,
webhook,
):
- app = app if app_type == "custom" else external_app
+ app = app_with_token if app_type == "custom" else external_app
app.permissions.add(permission_manage_staff)
webhook = webhook
diff --git a/saleor/graphql/app/tests/queries/test_apps.py b/saleor/graphql/app/tests/queries/test_apps.py
index ccbab61c36..ba448f3b3c 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,
+ app_with_token,
external_app,
app_filter,
count,
@@ -62,7 +62,11 @@ def test_apps_query(
external_app.save()
webhooks = Webhook.objects.bulk_create(
[
- Webhook(app=app, name="first", target_url="http://www.example.com/test"),
+ Webhook(
+ app=app_with_token,
+ 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.py
index 57078191f6..cad7cbe9f2 100644
--- a/saleor/graphql/app/types.py
+++ b/saleor/graphql/app/types.py
@@ -45,7 +45,7 @@ class AppToken(CountableDjangoObjectType):
@staticmethod
def resolve_auth_token(root: models.AppToken, _info, **_kwargs):
- return root.auth_token[-4:]
+ return root.raw_auth_token_last_4_chars
@key(fields="id")
diff --git a/saleor/graphql/core/tests/test_middleware.py b/saleor/graphql/core/tests/test_middleware.py
index 043b4576fa..f9d2ec299b 100644
--- a/saleor/graphql/core/tests/test_middleware.py
+++ b/saleor/graphql/core/tests/test_middleware.py
@@ -2,6 +2,7 @@ from unittest.mock import Mock
from django.urls import reverse
+from ....app.models import AppToken
from ...middleware import app_middleware
@@ -9,7 +10,7 @@ def test_app_middleware_accepts_api_requests(app, rf):
# Retrieve sample request object
request = rf.get(reverse("api"))
- token = app.tokens.first().auth_token
+ _token_inst, token = AppToken.objects.create_app_token(app=app)
request.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.py
index 0d7ed73ec4..b12aa36504 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 pytest
from django.utils import timezone
from .....account.models import User
-from .....app.models import App
+from .....app.models import App, AppToken
from .....core import JobStatus
from .....csv.models import ExportFile
from ....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)
- app2.tokens.create(name="Default")
+ AppToken.objects.create_app_token(app=app2, name="Default")
export_file_list[0].user = None
export_file_list[0].app = app
diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.py
index a971f3b496..0feca667bd 100644
--- a/saleor/graphql/middleware.py
+++ b/saleor/graphql/middleware.py
@@ -2,6 +2,7 @@ from typing import Optional
from django.conf import settings
from django.contrib.auth import authenticate
+from django.contrib.auth.hashers import check_password
from django.contrib.auth.models import AnonymousUser
from django.db.models import Exists, OuterRef
from django.utils.functional import SimpleLazyObject
@@ -28,11 +29,13 @@ class JWTMiddleware:
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 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 app_middleware(next, root, info, **kwargs):
diff --git a/saleor/graphql/tests/fixtures.py b/saleor/graphql/tests/fixtures.py
index 641e5f2a84..c01cf91f22 100644
--- a/saleor/graphql/tests/fixtures.py
+++ b/saleor/graphql/tests/fixtures.py
@@ -10,6 +10,7 @@ from django.shortcuts import reverse
from django.test.client import MULTIPART_CONTENT, Client
from ...account.models import User
+from ...app.models import AppToken
from ...core.jwt import create_access_token
from ...plugins.manager import get_plugins_manager
from ...tests.utils import flush_post_commit_hooks
@@ -32,13 +33,10 @@ class ApiClient(Client):
self._user = None
self.token = None
self.user = user
- self.app_token = None
+ self.app_token = kwargs.pop("app_token", None)
self.app = app
if 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 None
super().__init__(*args, **kwargs)
def _base_environ(self, **request):
@@ -120,7 +118,8 @@ class ApiClient(Client):
@pytest.fixture
def app_api_client(app):
- return ApiClient(app=app)
+ _token_inst, token = AppToken.objects.create_app_token(app=app, name="Default")
+ return ApiClient(app=app, app_token=token)
@pytest.fixture
diff --git a/saleor/graphql/tests/test_middleware.py b/saleor/graphql/tests/test_middleware.py
new file mode 100644
index 0000000000..737ff4c6d0
--- /dev/null
+++ b/saleor/graphql/tests/test_middleware.py
@@ -0,0 +1,35 @@
+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 None
diff --git a/saleor/plugins/webhook/tests/test_payment_webhook.py b/saleor/plugins/webhook/tests/test_payment_webhook.py
index ca063f0a86..db2efaae98 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 mock
import pytest
-from ....app.models import App
+from ....app.models import App, AppToken
from ....payment import PaymentError, TransactionKind
from ....payment.utils import create_payment_information
from ....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)
- app_2.tokens.create(name="Default")
+ AppToken.objects.create_app_token(app=app_2, 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.py
index dc4dab7c70..332210b20b 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -26,7 +26,7 @@ from PIL import Image
from prices import Money, TaxedMoney, fixed_discount
from ..account.models import Address, StaffNotificationRecipient, User
-from ..app.models import App, AppInstallation
+from ..app.models import App, AppInstallation, AppToken
from ..app.types import AppType
from ..attribute import AttributeEntityType, AttributeInputType, AttributeType
from ..attribute.models import (
@@ -3689,15 +3689,19 @@ def other_description_json():
@pytest.fixture
def app(db):
- app = App.objects.create(name="Sample app objects", is_active=True)
- app.tokens.create(name="Default")
+ 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")
return app
@pytest.fixture
def payment_app(db, permission_manage_payments):
app = App.objects.create(name="Payment App", is_active=True)
- app.tokens.create(name="Default")
+ AppToken.objects.create_app_token(app=app, name="Default")
app.permissions.add(permission_manage_payments)
webhook = Webhook.objects.create(
@@ -3729,7 +3733,7 @@ def external_app(db):
configuration_url="http://www.example.com/app-configuration/",
app_url="http://www.example.com/app/",
)
- app.tokens.create(name="Default")
+ AppToken.objects.create_app_token(app=app, name="Default")
return app