Skip to content

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

Wrap default token mutation with a custom one to handle errors nicely

Marcin Gębala85a4546a0514
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index c21b1ad887..7e0de682c3 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -5,6 +5,7 @@ from graphene_django.filter import DjangoFilterConnectionField
from ..page import models as page_models
from .core.filters import DistinctFilterSet
+from .core.mutations import CreateToken
from .page.resolvers import resolve_pages
from .page.types import Page
from .page.mutations import PageCreate, PageDelete, PageUpdate
@@ -88,7 +89,7 @@ class Query(graphene.ObjectType):
class Mutations(graphene.ObjectType):
- token_create = graphql_jwt.ObtainJSONWebToken.Field()
+ token_create = CreateToken.Field()
token_refresh = graphql_jwt.Refresh.Field()
category_create = CategoryCreateMutation.Field()
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index f75336862d..cc8aec6356 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -5,6 +5,8 @@ from django.core.exceptions import ImproperlyConfigured
from graphene.types.mutation import MutationOptions
from graphene_django.form_converter import convert_form_field
from graphene_django.registry import get_global_registry
+from graphql_jwt import ObtainJSONWebToken
+from graphql_jwt.exceptions import GraphQLJWTError
from graphql_jwt.decorators import staff_member_required
from ..utils import get_node
@@ -189,3 +191,23 @@ class StaffMemberRequiredMixin(graphene.Mutation):
def mutate(cls, root, info, *args, **kwargs):
mutate = permission_required(cls.permissions)(super().mutate)
return mutate(root, info, *args, **kwargs)
+
+
+class CreateToken(ObtainJSONWebToken):
+ """Mutation that authenticates a user and returns token.
+
+ It overrides the default graphql_jwt.ObtainJSONWebToken to wrap potential
+ authentication errors in our Error type, which is consistent to how rest of
+ the mutation works.
+ """
+
+ errors = graphene.List(Error)
+
+ @classmethod
+ def mutate(cls, root, info, **kwargs):
+ try:
+ result = super().mutate(root, info, **kwargs)
+ except GraphQLJWTError as e:
+ return CreateToken(errors=[Error(message=str(e))])
+ else:
+ return result
diff --git a/saleor/graphql/core/types.py b/saleor/graphql/core/types.py
index 27fb0c1403..025b72439f 100644
--- a/saleor/graphql/core/types.py
+++ b/saleor/graphql/core/types.py
@@ -31,7 +31,9 @@ class CountableDjangoObjectType(DjangoObjectType):
class Error(graphene.ObjectType):
field = graphene.String(
- description='Name of a field that caused the error.')
+ description="""Name of a field that caused the error. A value of
+ `null` indicates that the error isn't associated with a particular
+ field.""", required=False)
message = graphene.String(description='The error message.')
class Meta:
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index 831f2b04be..f78a964037 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -55,7 +55,7 @@ class ProductVariant(CountableDjangoObjectType):
price_override = graphene.Field(
Money,
description="""Override the base price of a product if necessary.
- A value of `null` indicates the the default product price is used.""")
+ A value of `null` indicates that the default product price is used.""")
attributes = graphene.List(
SelectedAttribute,
description='List of attributes assigned to this variant.')
diff --git a/tests/test_graphql.py b/tests/test_graphql.py
index ebd128ce3c..da15a677a1 100644
--- a/tests/test_graphql.py
+++ b/tests/test_graphql.py
@@ -17,6 +17,37 @@ from saleor.product.models import (
from .utils import get_graphql_content
+def test_create_token_mutation(admin_client, staff_user):
+ query = '''
+ mutation {
+ tokenCreate(email: "%(email)s", password: "%(password)s") {
+ token
+ errors {
+ field
+ message
+ }
+ }
+ }
+ '''
+ success_query = query % {'email': staff_user.email, 'password': 'password'}
+ response = admin_client.post(reverse('api'), {'query': success_query})
+ content = get_graphql_content(response)
+ assert 'errors' not in content
+ token_data = content['data']['tokenCreate']
+ assert token_data['token']
+ assert not token_data['errors']
+
+ error_query = query % {'email': staff_user.email, 'password': 'wat'}
+ response = admin_client.post(reverse('api'), {'query': error_query})
+ content = get_graphql_content(response)
+ assert 'errors' not in content
+ token_data = content['data']['tokenCreate']
+ assert not token_data['token']
+ errors = token_data['errors']
+ assert errors
+ assert not errors[0]['field']
+
+
def test_category_query(client, product):
category = Category.objects.first()
query = '''