Skip to content

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

Rebuild jwt-token to our implementation

Maciej Korycinski865755ee52a9
diff --git a/saleor/account/error_codes.py b/saleor/account/error_codes.py
index 9a39bb2e34..c4699ca037 100644
--- a/saleor/account/error_codes.py
+++ b/saleor/account/error_codes.py
@@ -27,6 +27,10 @@ class AccountErrorCode(Enum):
PASSWORD_TOO_SIMILAR = "password_too_similar"
REQUIRED = "required"
UNIQUE = "unique"
+ JWT_SIGNATURE_EXPIRED = "signature_has_expired"
+ JWT_INVALID_TOKEN = "invalid_token"
+ JWT_DECODE_ERROR = "decode_error"
+ JWT_MISSING_TOKEN = "missing_token"
class PermissionGroupErrorCode(Enum):
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index 681c0200e4..c869259e68 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,9 +1,3 @@
-import jwt
-from django.conf import settings
-from django.core.exceptions import ValidationError
-from django.utils import timezone
-
-from ..account.error_codes import AccountErrorCode
from ..checkout import AddressType
from ..core.utils import create_thumbnails
from ..plugins.manager import get_plugins_manager
@@ -78,27 +72,3 @@ def remove_staff_member(staff):
staff.save()
else:
staff.delete()
-
-
-def create_jwt_token(token_data):
- expiration_date = timezone.now() + timezone.timedelta(hours=1)
- token_kwargs = {"exp": expiration_date}
- token_kwargs.update(token_data)
- token = jwt.encode(token_kwargs, settings.SECRET_KEY, algorithm="HS256").decode()
- return token
-
-
-def decode_jwt_token(token):
- try:
- decoded_token = jwt.decode(
- token.encode(), settings.SECRET_KEY, algorithms=["HS256"]
- )
- except jwt.PyJWTError:
- raise ValidationError(
- {
- "token": ValidationError(
- "Invalid or expired token.", code=AccountErrorCode.INVALID
- )
- }
- )
- return decoded_token
diff --git a/saleor/core/auth_backend.py b/saleor/core/auth_backend.py
new file mode 100644
index 0000000000..78afc5e5e4
--- /dev/null
+++ b/saleor/core/auth_backend.py
@@ -0,0 +1,20 @@
+from ..account.models import User
+from .jwt import get_token_from_request, get_user_from_token
+
+
+class JSONWebTokenBackend:
+ def authenticate(self, request=None, **kwargs):
+ if request is None:
+ return None
+
+ token = get_token_from_request(request)
+ if not token:
+ return None
+ # user_can_authenticate
+ return get_user_from_token(token)
+
+ def get_user(self, user_id):
+ try:
+ return User.objects.get(email=user_id)
+ except User.DoesNotExist:
+ return None
diff --git a/saleor/core/jwt.py b/saleor/core/jwt.py
new file mode 100644
index 0000000000..35f04b72db
--- /dev/null
+++ b/saleor/core/jwt.py
@@ -0,0 +1,80 @@
+from datetime import datetime, timedelta
+from typing import List, Optional
+
+import graphene
+import jwt
+
+from saleor.account.models import User
+
+JWT_EXPIRATION_DELTA = timedelta(seconds=100)
+JWT_REFRESH_EXPIRATION_DELTA = timedelta(hours=100)
+JWT_SECRET = "ABC"
+JWT_ALGORITHM = "HS256"
+JWT_AUTH_HEADER = "HTTP_AUTHORIZATION"
+JWT_AUTH_HEADER_PREFIX = "JWT"
+JWT_ACCESS_TYPE = "access"
+JWT_REFRESH_TYPE = "refresh"
+JWT_REFRESH_TOKEN_COOKIE_NAME = "refreshToken"
+
+
+def jwt_base_payload(exp_delta):
+ payload = {
+ "exp": datetime.utcnow() + exp_delta,
+ "iat": datetime.utcnow(),
+ }
+ return payload
+
+
+def jwt_user_payload(
+ user, token_type, exp_delta, permissions: Optional[List[str]] = None
+):
+ payload = jwt_base_payload(exp_delta)
+ payload.update(
+ {
+ "email": user.email,
+ "type": token_type,
+ "user_id": graphene.Node.to_global_id("User", user.id),
+ "is_staff": user.is_staff,
+ "is_superuser": user.is_superuser,
+ }
+ )
+ if permissions:
+ payload["permissions"] = permissions
+ return payload
+
+
+def jwt_encode(payload):
+ return jwt.encode(payload, JWT_SECRET, JWT_ALGORITHM,).decode("utf-8")
+
+
+def jwt_decode(token):
+ return jwt.decode(token, JWT_SECRET, algorithms=JWT_ALGORITHM)
+
+
+def create_token(payload, exp_delta):
+ payload.update(jwt_base_payload(exp_delta))
+ return jwt_encode(payload)
+
+
+def create_access_token(user, permissions=None):
+ payload = jwt_user_payload(user, JWT_ACCESS_TYPE, JWT_EXPIRATION_DELTA, permissions)
+ return jwt_encode(payload)
+
+
+def create_refresh_token(user):
+ payload = jwt_user_payload(user, JWT_REFRESH_TYPE, JWT_REFRESH_EXPIRATION_DELTA)
+ return jwt_encode(payload)
+
+
+def get_token_from_request(request):
+ auth = request.META.get(JWT_AUTH_HEADER, "").split()
+ prefix = JWT_AUTH_HEADER_PREFIX
+
+ if len(auth) != 2 or auth[0].lower() != prefix.lower():
+ return None
+ return auth[1]
+
+
+def get_user_from_token(token):
+ payload = jwt_decode(token)
+ return User.objects.filter(email=payload["email"], is_active=True).first()
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 164d63fe2e..f05349c226 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -1,4 +1,5 @@
import logging
+from datetime import datetime
from django.conf import settings
from django.contrib.sites.models import Site
@@ -11,6 +12,7 @@ from django_countries.fields import Country
from ..discount.utils import fetch_discounts
from ..plugins.manager import get_plugins_manager
from . import analytics
+from .jwt import JWT_REFRESH_EXPIRATION_DELTA, JWT_REFRESH_TOKEN_COOKIE_NAME
from .utils import get_client_ip, get_country_by_ip, get_currency_for_country
logger = logging.getLogger(__name__)
@@ -116,3 +118,22 @@ def plugins(get_response):
return get_response(request)
return _plugins_middleware
+
+
+def jwt_refresh_token_middleware(get_response):
+ def middleware(request):
+ """Append generated refresh_token to response object."""
+ response = get_response(request)
+ jwt_refresh_token = getattr(request, "refresh_token", None)
+ if jwt_refresh_token:
+ expires = datetime.utcnow() + JWT_REFRESH_EXPIRATION_DELTA
+ response.set_cookie(
+ JWT_REFRESH_TOKEN_COOKIE_NAME,
+ jwt_refresh_token,
+ expires=expires,
+ httponly=True,
+ secure=True,
+ )
+ return response
+
+ return middleware
diff --git a/saleor/graphql/account/mutations/account.py b/saleor/graphql/account/mutations/account.py
index 4bf44f7afc..a06a309e02 100644
--- a/saleor/graphql/account/mutations/account.py
+++ b/saleor/graphql/account/mutations/account.py
@@ -1,4 +1,7 @@
+from datetime import timedelta
+
import graphene
+import jwt
from django.conf import settings
from django.contrib.auth import password_validation
from django.contrib.auth.tokens import default_token_generator
@@ -6,8 +9,8 @@ from django.core.exceptions import ValidationError
from ....account import emails, events as account_events, models, utils
from ....account.error_codes import AccountErrorCode
-from ....account.utils import create_jwt_token, decode_jwt_token
from ....checkout import AddressType
+from ....core.jwt import create_token, jwt_decode
from ....core.utils.url import validate_storefront_url
from ...account.enums import AddressTypeEnum
from ...account.types import Address, AddressInput, User
@@ -408,12 +411,12 @@ class RequestEmailChange(BaseMutation):
raise ValidationError(
{"redirect_url": error}, code=AccountErrorCode.INVALID
)
- token_kwargs = {
+ token_payload = {
"old_email": user.email,
"new_email": new_email,
"user_pk": user.pk,
}
- token = create_jwt_token(token_kwargs)
+ token = create_token(token_payload, timedelta(hours=1))
emails.send_user_change_email_url(redirect_url, user, new_email, token)
return RequestEmailChange(user=user)
@@ -435,13 +438,29 @@ class ConfirmEmailChange(BaseMutation):
def check_permissions(cls, context):
return context.user.is_authenticated
+ @classmethod
+ def get_token_payload(cls, token):
+ try:
+ payload = jwt_decode(token)
+ except jwt.PyJWTError:
+ raise ValidationError(
+ {
+ "token": ValidationError(
+ "Invalid or expired token.",
+ code=AccountErrorCode.JWT_INVALID_TOKEN,
+ )
+ }
+ )
+ return payload
+
@classmethod
def perform_mutation(cls, _root, info, **data):
user = info.context.user
token = data["token"]
- decoded_token = decode_jwt_token(token)
- new_email = decoded_token["new_email"]
- old_email = decoded_token["old_email"]
+
+ payload = cls.get_token_payload(token)
+ new_email = payload["new_email"]
+ old_email = payload["old_email"]
if models.User.objects.filter(email=new_email).exists():
raise ValidationError(
diff --git a/saleor/graphql/account/mutations/base.py b/saleor/graphql/account/mutations/base.py
index 9cfb0ee2da..cbbf1e9a14 100644
--- a/saleor/graphql/account/mutations/base.py
+++ b/saleor/graphql/account/mutations/base.py
@@ -18,13 +18,13 @@ from ...account.i18n import I18nMixin
from ...account.types import Address, AddressInput, User
from ...core.mutations import (
BaseMutation,
- CreateToken,
ModelDeleteMutation,
ModelMutation,
validation_error_to_error_type,
)
from ...core.types.common import AccountError
from ...meta.deprecated.mutations import ClearMetaBaseMutation, UpdateMetaBaseMutation
+from .jwt import CreateToken
BILLING_ADDRESS_FIELD = "default_billing_address"
SHIPPING_ADDRESS_FIELD = "default_shipping_address"
@@ -49,12 +49,16 @@ class SetPassword(CreateToken):
token = graphene.String(
description="A one-time token required to set the password.", required=True
)
+ email = graphene.String(required=True)
+ password = graphene.String(required=True)
class Meta:
description = (
"Sets the user's password from the token sent by email "
"using the RequestPasswordReset mutation."
)
+ error_type_class = AccountError
+ error_type_field = "account_errors"
@classmethod
def mutate(cls, root, info, **data):
diff --git a/saleor/graphql/account/mutations/jwt.py b/saleor/graphql/account/mutations/jwt.py
new file mode 100644
index 0000000000..383aa1714c
--- /dev/null
+++ b/saleor/graphql/account/mutations/jwt.py
@@ -0,0 +1,163 @@
+import graphene
+import jwt
+from django.contrib.auth import authenticate
+from django.core.exceptions import ValidationError
+from django.utils import timezone
+from graphene.types.generic import GenericScalar
+
+from ....account import models
+from ....account.error_codes import AccountErrorCode
+from ....core.jwt import (
+ JWT_REFRESH_TOKEN_COOKIE_NAME,
+ create_access_token,
+ create_refresh_token,
+ jwt_decode,
+)
+from ...core.mutations import BaseMutation
+from ...core.types.common import AccountError
+from ..types import User
+
+
+def get_payload(token):
+ try:
+ payload = jwt_decode(token)
+ except jwt.ExpiredSignature:
+ raise ValidationError(
+ "Signature has expired", code=AccountErrorCode.JWT_SIGNATURE_EXPIRED.value
+ )
+ except jwt.DecodeError:
+ raise ValidationError(
+ "Error decoding signature", code=AccountErrorCode.JWT_DECODE_ERROR.value
+ )
+ except jwt.InvalidTokenError:
+ raise ValidationError(
+ "Invalid token", code=AccountErrorCode.JWT_INVALID_TOKEN.value
+ )
+ return payload
+
+
+class CreateToken(BaseMutation):
+ """Mutation that authenticates a user and returns token and user data."""
+
+ class Arguments:
+ email = graphene.String(required=True)
+ password = graphene.String(required=True)
+
+ class Meta:
+ description = "Create JWT token."
+ error_type_class = AccountError
+ error_type_field = "account_errors"
+
+ token = graphene.String(description="JWT token, required to authenticate.")
+ refresh_token = graphene.String(
+ description="JWT refresh token, required to re-generate access token."
+ )
+ user = graphene.Field(User, description="A user instance.")
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ user = authenticate(
+ request=info.context, username=data["email"], password=data["password"],
+ )
+ if not user:
+ raise ValidationError(
+ {
+ "email": ValidationError(
+ "Please, enter valid credentials",
+ code=AccountErrorCode.INVALID_CREDENTIALS.value,
+ )
+ }
+ )
+ access_token = create_access_token(user)
+ refresh_token = create_refresh_token(user)
+ info.context.refresh_token = refresh_token
+ info.context._cached_user = user
+ user.last_login = timezone.now()
+ user.save(update_fields=["last_login"])
+ return cls(
+ errors=[], user=user, token=access_token, refresh_token=refresh_token
+ )
+
+
+class RefreshToken(BaseMutation):
+ """Mutation that refresh user token and returns token and user data."""
+
+ token = graphene.String(description="JWT token, required to authenticate.")
+ user = graphene.Field(User, description="A user instance.")
+
+ class Arguments:
+ refresh_token = graphene.String(required=False, description="Refresh token.")
+
+ class Meta:
+ description = (
+ "Refresh JWT token. Mutation tries to take refreshToken from "
+ f"the http-only cookie {JWT_REFRESH_TOKEN_COOKIE_NAME}. If it "
+ "fails it will try to take refreshToken provided as an argument."
+ )
+ error_type_class = AccountError
+ error_type_field = "account_errors"
+
+ @classmethod
+ def get_refresh_token_payload(cls, refresh_token):
+ try:
+ payload = get_payload(refresh_token)
+ except ValidationError as e:
+ raise ValidationError({"refreshToken": e})
+ return payload
+
+ @classmethod
+ def get_refresh_token(cls, info, data):
+ request = info.context
+ refresh_token = request.COOKIES.get(JWT_REFRESH_TOKEN_COOKIE_NAME, None)
+ refresh_token = refresh_token or data.get("refresh_token")
+ return refresh_token
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ refresh_token = cls.get_refresh_token(info, data)
+ if not refresh_token:
+ raise ValidationError(
+ {
+ "refreshToken": ValidationError(
+ "Missing refreshToken",
+ code=AccountErrorCode.JWT_MISSING_TOKEN.value,
+ )
+ }
+ )
+ payload = cls.get_refresh_token_payload(refresh_token)
+ user = models.User.objects.filter(email=payload["email"]).first()
+ token = create_access_token(user)
+ return cls(errors=[], user=user, token=token)
+
+
+class VerifyToken(BaseMutation):
+ """Mutation that confirms if token is valid and also returns user data."""
+
+ user = graphene.Field(User, description="User assigned to token.")
+ is_valid = graphene.Boolean(
+ default_value=False, description="Determine if token is valid or not."
+ )
+ payload = GenericScalar(description="JWT payload.")
+
+ class Arguments:
+ token = graphene.String(required=True, description="JWT token to validate.")
+
+ class Meta:
+ description = "Verify JWT token."
+ error_type_class = AccountError
+ error_type_field = "account_errors"
+
+ @classmethod
+ def get_payload(cls, token):
+ try:
+ payload = get_payload(token)
+ except ValidationError as e:
+ raise ValidationError({"token": e})
+ return payload
+
+ @classmethod
+ def perform_mutation(cls, root, info, **data):
+ token = data["token"]
+ payload = cls.get_payload(token)
+ user = models.User.objects.filter(email=payload["email"]).first()
+ return cls(errors=[], user=user, is_valid=True, payload=payload)
diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.py
index 9053a8b338..aa97faf63f 100644
--- a/saleor/graphql/account/schema.py
+++ b/saleor/graphql/account/schema.py
@@ -40,6 +40,7 @@ from .mutations.base import (
UserClearMeta,
UserUpdateMeta,
)
+from .mutations.jwt import CreateToken, RefreshToken, VerifyToken
from .mutations.permission_group import (
PermissionGroupCreate,
PermissionGroupDelete,
@@ -219,6 +220,10 @@ class AccountQueries(graphene.ObjectType):
class AccountMutations(graphene.ObjectType):
# Base mutations
+ token_create = CreateToken.Field()
+ token_refresh = RefreshToken.Field()
+ token_verify = VerifyToken.Field()
+
request_password_reset = RequestPasswordReset.Field()
confirm_account = ConfirmAccount.Field()
set_password = SetPassword.Field()
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index b4e2290d3d..c2877afa1a 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -3,7 +3,7 @@ from graphene_federation import build_schema
from .account.schema import AccountMutations, AccountQueries
from .app.schema import AppMutations, AppQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
-from .core.schema import CoreMutations, CoreQueries
+from .core.schema import CoreQueries
from .discount.schema import DiscountMutations, DiscountQueries
from .giftcard.schema import GiftCardMutations, GiftCardQueries
from .menu.schema import MenuMutations, MenuQueries
@@ -47,7 +47,6 @@ class Mutation(
AccountMutations,
AppMutations,
CheckoutMutations,
- CoreMutations,
DiscountMutations,
PluginsMutations,
GiftCardMutations,
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 799feb6ed8..876deb1fb8 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -2,28 +2,21 @@ from itertools import chain
from typing import Tuple, Union
import graphene
-from django.contrib.auth import get_user_model
from django.core.exceptions import (
NON_FIELD_ERRORS,
ImproperlyConfigured,
ValidationError,
)
from django.db.models.fields.files import FileField
-from django.utils import timezone
from graphene import ObjectType
from graphene.types.mutation import MutationOptions
from graphene_django.registry import get_global_registry
from graphql.error import GraphQLError
-from graphql_jwt import ObtainJSONWebToken, Refresh, Verify
-from graphql_jwt.exceptions import JSONWebTokenError, PermissionDenied
+from graphql_jwt.exceptions import PermissionDenied
-from ...account import models
-from ...account.error_codes import AccountErrorCode
from ...core.permissions import AccountPermissions
-from ..account.types import User
from ..utils import get_nodes
from .types import Error, Upload
-from .types.common import AccountError
from .utils import from_global_id_strict_type, snake_to_camel_case
from .utils.error_codes import get_error_code_from_error
@@ -604,95 +597,3 @@ class ModelBulkDeleteMutation(BaseBulkMutation):
@classmethod
def bulk_action(cls, queryset):
queryset.delete()
-
-
-class CreateToken(ObtainJSONWebToken):
- """Mutation that authenticates a user and returns token and user data.
-
- It overrides the default graphql_jwt.ObtainJSONWebToken to wrap potential
- authentication errors in our Error type, which is consistent to how the rest of
- the mutation works.
- """
-
- errors = graphene.List(
- graphene.NonNull(Error),
- required=True,
- deprecation_reason=(
- "Use typed errors with error codes. This field will be removed after "
- "2020-07-31."
- ),
- )
- account_errors = graphene.List(
- graphene.NonNull(AccountError),
- description="List of errors that occurred executing the mutation.",
- required=True,
- )
- user = graphene.Field(User, description="A user instance.")
-
- @classmethod
- def mutate(cls, root, info, **kwargs):
- try:
- result = super().mutate(root, info, **kwargs)
- except JSONWebTokenError as e:
- errors = [Error(message=str(e))]
- account_errors = [
- AccountError(
- field="email",
- message="Please, enter valid credentials",
- code=AccountErrorCode.INVALID_CREDENTIALS,
- )
- ]
- return CreateToken(errors=errors, account_errors=account_errors)
- except ValidationError as e:
- errors = validation_error_to_error_type(e)
- return cls.handle_typed_errors(errors)
- else:
- user = result.user
- user.last_login = timezone.now()
- user.save(update_fields=["last_login"])
- return result
-
- @classmethod
- def handle_typed_errors(cls, errors: list):
- account_errors = [
- AccountError(field=e.field, message=e.message, code=code)
- for e, code, _params in errors
- ]
- return cls(errors=[e[0] for e in errors], account_errors=account_errors)
-
- @classmethod
- def resolve(cls, root, info, **kwargs):
- return cls(user=info.context.user, errors=[], account_errors=[])
-
-
-class RefreshToken(Refresh):
- """Mutation that refresh user token.
-
- It overrides the default graphql_jwt.Refresh to update user's last_login field.
- """
-
- @classmethod
- def mutate(cls, root, info, **kwargs):
- result = super().mutate(root, info, **kwargs)
- user = graphene.Node.get_node_from_global_id(info, result.payload["user_id"])
- user.last_login = timezone.now()
- user.save(update_fields=["last_login"])
- return result
-
-
-class VerifyToken(Verify):
- """Mutation that confirms if token is valid and also returns user data."""
-
- user = graphene.Field(User)
-
- def resolve_user(self, _info, **_kwargs):
- username_field = get_user_model().USERNAME_FIELD
- kwargs = {username_field: self.payload.get(username_field)}
- return models.User.objects.get(**kwargs)
-
- @classmethod
- def mutate(cls, root, info, token, **kwargs):
- try:
- return super().mutate(root, info, token, **kwargs)
- except JSONWebTokenError:
- return None
diff --git a/saleor/graphql/core/schema.py b/saleor/graphql/core/schema.py
index 3d41c6388f..509381b285 100644
--- a/saleor/graphql/core/schema.py
+++ b/saleor/graphql/core/schema.py
@@ -1,15 +1,8 @@
import graphene
-from .mutations import CreateToken, RefreshToken, VerifyToken
from .types.common import TaxType
-class CoreMutations(graphene.ObjectType):
- token_create = CreateToken.Field()
- token_refresh = RefreshToken.Field()
- token_verify = VerifyToken.Field()
-
-
class CoreQueries(graphene.ObjectType):
tax_types = graphene.List(
TaxType, description="List of all tax rates available from tax gateway."
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index 384cbcbe26..ec66e0630a 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -34,7 +34,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
app_models.App: app_types.App,
account_models.User: account_types.User,
}
- return MODEL_TO_TYPE_MAP.get(type(instance), None)
+ return MODEL_TO_TYPE_MAP.get(instance.__class__, None)
def resolve_metadata(metadata: dict):
diff --git a/saleor/graphql/middleware.py b/saleor/graphql/middleware.py
index 65f78d047c..55a4c4954c 100644
--- a/saleor/graphql/middleware.py
+++ b/saleor/graphql/middleware.py
@@ -3,10 +3,10 @@ from typing import Optional
import opentracing
import opentracing.tags
from django.conf import settings
+from django.contrib.auth import authenticate
from django.contrib.auth.models import AnonymousUser
from django.utils.functional import SimpleLazyObject
from graphql import ResolveInfo
-from graphql_jwt.middleware import JSONWebTokenMiddleware
from ..app.models import App
from ..core.exceptions import ReadOnlyException
@@ -14,13 +14,21 @@ from ..core.tracing import should_trace
from .views import API_PATH, GraphQLView
-class JWTMiddleware(JSONWebTokenMiddleware):
+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 not hasattr(request, "user"):
- request.user = AnonymousUser()
- return super().resolve(next, root, info, **kwargs)
+ def user():
+ return get_user(request) or AnonymousUser()
+
+ request.user = SimpleLazyObject(lambda: user())
+ return next(root, info, **kwargs)
class OpentracingGrapheneMiddleware:
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 3d88863652..56954dba52 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -62,6 +62,10 @@ enum AccountErrorCode {
PASSWORD_TOO_SIMILAR
REQUIRED
UNIQUE
+ JWT_SIGNATURE_EXPIRED
+ JWT_INVALID_TOKEN
+ JWT_DECODE_ERROR
+ JWT_MISSING_TOKEN
}
input AccountInput {
@@ -1437,10 +1441,11 @@ type CountryDisplay {
}
type CreateToken {
- token: String
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- accountErrors: [AccountError!]!
+ token: String
+ refreshToken: String
user: User
+ accountErrors: [AccountError!]!
}
type CreditCard {
@@ -2443,9 +2448,6 @@ type Mutation {
voucherCataloguesAdd(id: ID!, input: CatalogueInput!): VoucherAddCatalogues
voucherCataloguesRemove(id: ID!, input: CatalogueInput!): VoucherRemoveCatalogues
voucherTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): VoucherTranslate
- tokenCreate(email: String!, password: String!): CreateToken
- tokenRefresh(token: String!): RefreshToken
- tokenVerify(token: String!): VerifyToken
checkoutAddPromoCode(checkoutId: ID!, promoCode: String!): CheckoutAddPromoCode
checkoutBillingAddressUpdate(billingAddress: AddressInput!, checkoutId: ID!): CheckoutBillingAddressUpdate
checkoutComplete(checkoutId: ID!, redirectUrl: String, storeSource: Boolean = false): CheckoutComplete
@@ -2469,9 +2471,12 @@ type Mutation {
appDelete(id: ID!): AppDelete
appTokenCreate(input: AppTokenInput!): AppTokenCreate
appTokenDelete(id: ID!): AppTokenDelete
+ tokenCreate(email: String!, password: String!): CreateToken
+ tokenRefresh(refreshToken: String): RefreshToken
+ tokenVerify(token: String!): VerifyToken
requestPasswordReset(email: String!, redirectUrl: String!): RequestPasswordReset
confirmAccount(email: String!, token: String!): ConfirmAccount
- setPassword(token: String!, email: String!, password: String!): SetPassword
+ setPassword(email: String!, password: String!, token: String!): SetPassword
passwordChange(newPassword: String!, oldPassword: String!): PasswordChange
requestEmailChange(newEmail: String!, password: String!, redirectUrl: String!): RequestEmailChange
confirmEmailChange(token: String!): ConfirmEmailChange
@@ -3952,8 +3957,10 @@ type ReducedRate {
}
type RefreshToken {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
token: String
- payload: GenericScalar
+ user: User
+ accountErrors: [AccountError!]!
}
input ReorderInput {
@@ -4203,10 +4210,11 @@ type ServiceAccountUpdatePrivateMeta {
}
type SetPassword {
- token: String
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- accountErrors: [AccountError!]!
+ token: String
+ refreshToken: String
user: User
+ accountErrors: [AccountError!]!
}
type ShippingError {
@@ -4898,8 +4906,11 @@ type VariantPricingInfo {
}
type VerifyToken {
- payload: GenericScalar
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
user: User
+ isValid: Boolean
+ payload: GenericScalar
+ accountErrors: [AccountError!]!
}
type Voucher implements Node {
diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.py
index d93294a47e..8b5ad8e5c2 100644
--- a/saleor/graphql/utils/__init__.py
+++ b/saleor/graphql/utils/__init__.py
@@ -5,7 +5,6 @@ from django.db.models import Value
from django.db.models.functions import Concat
from graphene_django.registry import get_global_registry
from graphql.error import GraphQLError
-from graphql_jwt.utils import jwt_payload
from graphql_relay import from_global_id
from ..core.enums import PermissionEnum
@@ -123,14 +122,6 @@ def format_permissions_for_display(permissions):
return formatted_permissions
-def create_jwt_payload(user, context=None):
- payload = jwt_payload(user, context)
- payload["user_id"] = graphene.Node.to_global_id("User", user.id)
- payload["is_staff"] = user.is_staff
- payload["is_superuser"] = user.is_superuser
- return payload
-
-
def get_user_or_app_from_context(context):
# order is important
# app can be None but user if None then is passed as anonymous
diff --git a/saleor/graphql/views.py b/saleor/graphql/views.py
index f0a1755b29..44eb9b1476 100644
--- a/saleor/graphql/views.py
+++ b/saleor/graphql/views.py
@@ -22,7 +22,8 @@ from graphql.error import (
format_error as format_graphql_error,
)
from graphql.execution import ExecutionResult
-from graphql_jwt.exceptions import JSONWebTokenError
+from graphql_jwt.exceptions import PermissionDenied
+from jwt.exceptions import PyJWTError
from ..core.exceptions import ReadOnlyException
from ..core.utils import is_valid_ipv4, is_valid_ipv6
@@ -59,7 +60,8 @@ class GraphQLView(View):
middleware = None
root_value = None
- HANDLED_EXCEPTIONS = (GraphQLError, JSONWebTokenError, ReadOnlyException)
+ # TODO Remove unneeded exceptions
+ HANDLED_EXCEPTIONS = (GraphQLError, PyJWTError, ReadOnlyException, PermissionDenied)
def __init__(
self, schema=None, executor=None, middleware=None, root_value=None, backend=None
diff --git a/saleor/settings.py b/saleor/settings.py
index 86200069c2..662d14063f 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -1,7 +1,6 @@
import ast
import os.path
import warnings
-from datetime import timedelta
import dj_database_url
import dj_email_url
@@ -212,6 +211,7 @@ MIDDLEWARE = [
"saleor.core.middleware.currency",
"saleor.core.middleware.site",
"saleor.core.middleware.plugins",
+ "saleor.core.middleware.jwt_refresh_token_middleware",
]
INSTALLED_APPS = [
@@ -378,7 +378,6 @@ PAYMENT_HOST = get_host
PAYMENT_MODEL = "order.Payment"
MAX_CHECKOUT_LINE_QUANTITY = int(os.environ.get("MAX_CHECKOUT_LINE_QUANTITY", 50))
-
TEST_RUNNER = "tests.runner.PytestTestRunner"
PLAYGROUND_ENABLED = get_bool_from_env("PLAYGROUND_ENABLED", True)
@@ -456,19 +455,10 @@ DEFAULT_PLACEHOLDER = "images/placeholder255x255.png"
SEARCH_BACKEND = "saleor.search.backends.postgresql"
AUTHENTICATION_BACKENDS = [
- "graphql_jwt.backends.JSONWebTokenBackend",
+ "saleor.core.auth_backend.JSONWebTokenBackend",
"django.contrib.auth.backends.ModelBackend",
]
-# Django GraphQL JWT settings
-GRAPHQL_JWT = {
- "JWT_PAYLOAD_HANDLER": "saleor.graphql.utils.create_jwt_payload",
- # How long until a token expires, default is 5m from graphql_jwt.settings
- "JWT_EXPIRATION_DELTA": timedelta(minutes=5),
- # Whether the JWT tokens should expire or not
- "JWT_VERIFY_EXPIRATION": get_bool_from_env("JWT_VERIFY_EXPIRATION", False),
-}
-
# CELERY SETTINGS
CELERY_BROKER_URL = (
os.environ.get("CELERY_BROKER_URL", os.environ.get("CLOUDAMQP_URL")) or ""
diff --git a/tests/api/conftest.py b/tests/api/conftest.py
index 41de78a898..13e1becf04 100644
--- a/tests/api/conftest.py
+++ b/tests/api/conftest.py
@@ -7,10 +7,10 @@ from django.contrib.auth.models import AnonymousUser
from django.core.serializers.json import DjangoJSONEncoder
from django.shortcuts import reverse
from django.test.client import MULTIPART_CONTENT, Client
-from graphql_jwt.shortcuts import get_token
from saleor.account.models import User
from saleor.app.models import App
+from saleor.core.jwt import create_access_token
from saleor.graphql.views import handled_errors_logger, unhandled_errors_logger
from ..utils import flush_post_commit_hooks
@@ -31,7 +31,7 @@ class ApiClient(Client):
self.app_token = None
self.app = app
if not user.is_anonymous:
- self.token = get_token(user)
+ self.token = create_access_token(user)
elif app:
token = app.tokens.first()
self.app_token = token.auth_token if token else None
@@ -53,7 +53,7 @@ class ApiClient(Client):
def user(self, user):
self._user = user
if not user.is_anonymous:
- self.token = get_token(user)
+ self.token = create_access_token(user)
def post(self, data=None, **kwargs):
"""Send a POST request.
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index 09c79f8b7d..07c4771d10 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -1,10 +1,10 @@
import re
import uuid
from collections import defaultdict
+from datetime import timedelta
from unittest.mock import ANY, MagicMock, Mock, patch
import graphene
-import jwt
import pytest
from django.contrib.auth.models import Group
from django.contrib.auth.tokens import default_token_generator
@@ -12,15 +12,14 @@ from django.core.exceptions import ValidationError
from django.core.files import File
from django.core.validators import URLValidator
from django.test import override_settings
-from django.utils import timezone
from freezegun import freeze_time
from prices import Money
from saleor.account import events as account_events
from saleor.account.error_codes import AccountErrorCode
from saleor.account.models import Address, User
-from saleor.account.utils import create_jwt_token
from saleor.checkout import AddressType
+from saleor.core.jwt import create_token
from saleor.core.permissions import AccountPermissions, OrderPermissions
from saleor.graphql.account.mutations.base import INVALID_TOKEN
from saleor.graphql.account.mutations.staff import (
@@ -79,80 +78,6 @@ def query_staff_users_with_filter():
return query
-def test_create_token_mutation(api_client, staff_user, settings):
- query = """
- mutation TokenCreate($email: String!, $password: String!) {
- tokenCreate(email: $email, password: $password) {
- token
- errors {
- field
- message
- }
- }
- }
- """
- variables = {"email": staff_user.email, "password": "password"}
- time = timezone.now()
- with freeze_time(time):
- response = api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- token_data = content["data"]["tokenCreate"]
- token = jwt.decode(token_data["token"], settings.SECRET_KEY)
- staff_user.refresh_from_db()
- assert staff_user.last_login == time
- assert token["email"] == staff_user.email
- assert token["user_id"] == graphene.Node.to_global_id("User", staff_user.id)
-
- assert token_data["errors"] == []
-
- incorrect_variables = {"email": staff_user.email, "password": "incorrect"}
- response = api_client.post_graphql(query, incorrect_variables)
- content = get_graphql_content(response)
- token_data = content["data"]["tokenCreate"]
- errors = token_data["errors"]
- assert errors
- assert not errors[0]["field"]
- assert not token_data["token"]
-
-
-def test_token_create_user_data(permission_manage_orders, staff_api_client, staff_user):
- query = """
- mutation TokenCreate($email: String!, $password: String!) {
- tokenCreate(email: $email, password: $password) {
- user {
- id
- email
- permissions {
- code
- name
- }
- userPermissions {
- code
- name
- }
- }
- }
- }
- """
-
- permission = permission_manage_orders
- staff_user.user_permissions.add(permission)
- name = permission.name
- user_id = graphene.Node.to_global_id("User", staff_user.id)
-
- variables = {"email": staff_user.email, "password": "password"}
- response = staff_api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
- token_data = content["data"]["tokenCreate"]
- assert token_data["user"]["id"] == user_id
- assert token_data["user"]["email"] == staff_user.email
- assert token_data["user"]["userPermissions"][0]["name"] == name
- assert token_data["user"]["userPermissions"][0]["code"] == "MANAGE_ORDERS"
- # deprecated, to remove in #5389
- assert token_data["user"]["permissions"][0]["name"] == name
- assert token_data["user"]["permissions"][0]["code"] == "MANAGE_ORDERS"
-
-
FULL_USER_QUERY = """
query User($id: ID!) {
user(id: $id) {
@@ -2484,6 +2409,7 @@ SET_PASSWORD_MUTATION = """
id
}
token
+ refreshToken
}
}
"""
@@ -4193,12 +4119,13 @@ mutation emailUpdate($token: String!) {
def test_email_update(user_api_client, customer_user):
new_email = "[email protected]"
- token_kwargs = {
+ payload = {
"old_email": customer_user.email,
"new_email": new_email,
"user_pk": customer_user.pk,
}
- token = create_jwt_token(token_kwargs)
+
+ token = create_token(payload, timedelta(hours=1))
variables = {"token": token}
response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)
@@ -4208,12 +4135,12 @@ def test_email_update(user_api_client, customer_user):
def test_email_update_to_existing_email(user_api_client, customer_user, staff_user):
- token_kwargs = {
+ payload = {
"old_email": customer_user.email,
"new_email": staff_user.email,
"user_pk": customer_user.pk,
}
- token = create_jwt_token(token_kwargs)
+ token = create_token(payload, timedelta(hours=1))
variables = {"token": token}
response = user_api_client.post_graphql(EMAIL_UPDATE_QUERY, variables)
diff --git a/tests/api/test_account_mutations_jwt.py b/tests/api/test_account_mutations_jwt.py
new file mode 100644
index 0000000000..22ef05781d
--- /dev/null
+++ b/tests/api/test_account_mutations_jwt.py
@@ -0,0 +1,264 @@
+from datetime import datetime, timedelta
+
+import graphene
+from freezegun import freeze_time
+from jwt import decode
+
+from saleor.account.error_codes import AccountErrorCode
+from saleor.core.jwt import (
+ JWT_ACCESS_TYPE,
+ JWT_ALGORITHM,
+ JWT_EXPIRATION_DELTA,
+ JWT_REFRESH_EXPIRATION_DELTA,
+ JWT_REFRESH_TOKEN_COOKIE_NAME,
+ JWT_REFRESH_TYPE,
+ JWT_SECRET,
+ create_access_token,
+ create_refresh_token,
+)
+from tests.api.utils import get_graphql_content
+
+MUTATION_CREATE_TOKEN = """
+ mutation tokenCreate($email: String!, $password: String!){
+ tokenCreate(email: $email, password: $password) {
+ token
+ refreshToken
+ user {
+ email
+ }
+ errors {
+ field
+ message
+ }
+ accountErrors {
+ field
+ message
+ code
+ }
+ }
+ }
+"""
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_create_token(api_client, customer_user):
+ variables = {"email": customer_user.email, "password": customer_user._password}
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["tokenCreate"]
+
+ user_email = data["user"]["email"]
+ assert customer_user.email == user_email
+ assert content["data"]["tokenCreate"]["accountErrors"] == []
+
+ token = data["token"]
+ refreshToken = data["refreshToken"]
+
+ payload = decode(token, JWT_SECRET, algorithms=JWT_ALGORITHM)
+ assert payload["email"] == customer_user.email
+ assert payload["user_id"] == graphene.Node.to_global_id("User", customer_user.id)
+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ expected_expiration_datetime = datetime.utcnow() + JWT_EXPIRATION_DELTA
+ assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert payload["type"] == JWT_ACCESS_TYPE
+
+ payload = decode(refreshToken, JWT_SECRET, algorithms=JWT_ALGORITHM)
+ assert payload["email"] == customer_user.email
+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ expected_expiration_datetime = datetime.utcnow() + JWT_REFRESH_EXPIRATION_DELTA
+ assert datetime.fromtimestamp(payload["exp"]) == expected_expiration_datetime
+ assert payload["type"] == JWT_REFRESH_TYPE
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_create_token_sets_cookie(api_client, customer_user):
+ variables = {"email": customer_user.email, "password": customer_user._password}
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+
+ expected_refresh_token = create_refresh_token(customer_user)
+ refresh_token = response.cookies["refreshToken"]
+ assert refresh_token.value == expected_refresh_token
+ expected_expires = datetime.utcnow() + JWT_REFRESH_EXPIRATION_DELTA
+ expected_expires += timedelta(seconds=1)
+ expires = datetime.strptime(refresh_token["expires"], "%a, %d %b %Y %H:%M:%S %Z")
+ assert expires == expected_expires
+ assert refresh_token["httponly"]
+ assert refresh_token["secure"]
+
+
+def test_create_token_invalid_password(api_client, customer_user):
+ variables = {"email": customer_user.email, "password": "wrongpassword"}
+ expected_error_code = AccountErrorCode.INVALID_CREDENTIALS.value.upper()
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+ response_error = content["data"]["tokenCreate"]["accountErrors"][0]
+ assert response_error["code"] == expected_error_code
+ assert response_error["field"] == "email"
+
+
+def test_create_token_invalid_email(api_client, customer_user):
+ variables = {"email": "wrongemail", "password": "wrongpassword"}
+ expected_error_code = AccountErrorCode.INVALID_CREDENTIALS.value.upper()
+ response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
+ content = get_graphql_content(response)
+ response_error = content["data"]["tokenCreate"]["accountErrors"][0]
+ assert response_error["code"] == expected_error_code
+ assert response_error["field"] == "email"
+
+
+MUTATION_TOKEN_VERIFY = """
+ mutation tokenVerify($token: String!){
+ tokenVerify(token: $token){
+ isValid
+ user{
+ email
+ }
+ accountErrors{
+ code
+ }
+ }
+ }
+"""
+
+
+def test_verify_token(api_client, customer_user):
+ variables = {"token": create_access_token(customer_user)}
+ response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["tokenVerify"]
+ assert data["isValid"]
+ user_email = content["data"]["tokenVerify"]["user"]["email"]
+ assert customer_user.email == user_email
+
+
+def test_verify_token_incorrect_token(api_client):
+ variables = {"token": "incorrect_token"}
+ response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)
+ content = get_graphql_content(response)
+ data = content["data"]["tokenVerify"]
+ errors = data["accountErrors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == AccountErrorCode.JWT_DECODE_ERROR.name
+ assert not data["isValid"]
+ assert not data["user"]
+
+
+MUTATION_TOKEN_REFRESH = """
+ mutation tokenRefresh($token: String){
+ tokenRefresh(refreshToken: $token){
+ token
+ accountErrors{
+ code
+ }
+ }
+ }
+"""
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_token_get_token_from_cookie(
+ api_client, customer_user,
+):
+ refresh_token = create_refresh_token(customer_user)
+ variables = {"token": None}
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["tokenRefresh"]
+ errors = data["accountErrors"]
+
+ assert not errors
+ token = data.get("token")
+ assert token
+ payload = decode(token, JWT_SECRET, algorithms=JWT_ALGORITHM)
+ assert payload["email"] == customer_user.email
+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ assert (
+ datetime.fromtimestamp(payload["exp"])
+ == datetime.utcnow() + JWT_EXPIRATION_DELTA
+ )
+ assert payload["type"] == JWT_ACCESS_TYPE
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_token_get_token_from_input(api_client, customer_user):
+ refresh_token = create_refresh_token(customer_user)
+ variables = {"token": refresh_token}
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["tokenRefresh"]
+ errors = data["accountErrors"]
+
+ assert not errors
+ token = data.get("token")
+ assert token
+ payload = decode(token, JWT_SECRET, algorithms=JWT_ALGORITHM)
+ assert payload["email"] == customer_user.email
+ assert datetime.fromtimestamp(payload["iat"]) == datetime.utcnow()
+ assert (
+ datetime.fromtimestamp(payload["exp"])
+ == datetime.utcnow() + JWT_EXPIRATION_DELTA
+ )
+ assert payload["type"] == JWT_ACCESS_TYPE
+
+
+def test_refresh_token_get_token_missing_token(api_client, customer_user):
+ variables = {"token": None}
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+ content = get_graphql_content(response)
+
+ data = content["data"]["tokenRefresh"]
+ errors = data["accountErrors"]
+
+ token = data.get("token")
+ assert not token
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == AccountErrorCode.JWT_MISSING_TOKEN.name
+
+
+def test_refresh_token_when_expired(api_client, customer_user):
+ with freeze_time("2018-05-31 12:00:01"):
+ refresh_token = create_refresh_token(customer_user)
+
+ variables = {"token": None}
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
+
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+
+ content = get_graphql_content(response)
+
+ data = content["data"]["tokenRefresh"]
+ errors = data["accountErrors"]
+
+ token = data.get("token")
+ assert not token
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == AccountErrorCode.JWT_SIGNATURE_EXPIRED.name
+
+
+def test_refresh_token_when_incorrect_token(api_client, customer_user):
+ refresh_token = create_refresh_token(customer_user)
+
+ variables = {"token": None}
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token + "wrong-token"
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
+
+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
+
+ content = get_graphql_content(response)
+
+ data = content["data"]["tokenRefresh"]
+ errors = data["accountErrors"]
+
+ token = data.get("token")
+ assert not token
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == AccountErrorCode.JWT_DECODE_ERROR.name
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index f9c7616798..f667f9ac90 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -199,10 +199,10 @@ QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = """
@pytest.mark.parametrize("is_staff", (False, True))
def test_resolve_attributes_with_hidden(
user_api_client,
+ staff_api_client,
product,
color_attribute,
size_attribute,
- staff_user,
is_staff,
permission_manage_products,
):
@@ -221,10 +221,10 @@ def test_resolve_attributes_with_hidden(
expected_variant_attribute_count = variant.attributes.count() - 1
if is_staff:
- api_client.user = staff_user
+ api_client = staff_api_client
+ api_client.user.user_permissions.add(permission_manage_products)
expected_product_attribute_count += 1
expected_variant_attribute_count += 1
- staff_user.user_permissions.add(permission_manage_products)
# Hide one product and variant attribute from the storefront
for attribute in (product_attribute, variant_attribute):
diff --git a/tests/api/test_core.py b/tests/api/test_core.py
index 9abd4bbc53..09cc4af539 100644
--- a/tests/api/test_core.py
+++ b/tests/api/test_core.py
@@ -7,9 +7,7 @@ from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ImproperlyConfigured, ValidationError
from django.utils import timezone
from graphene import InputField
-from graphql_jwt.shortcuts import get_token
-from saleor.account.error_codes import AccountErrorCode
from saleor.graphql.core.enums import ReportingPeriod
from saleor.graphql.core.filters import EnumFilter
from saleor.graphql.core.mutations import BaseMutation
@@ -288,83 +286,6 @@ def test_mutation_invalid_permission_in_meta(_mocked, should_fail, permissions_v
assert exc.value.args[0] == "Permissions should be a tuple or a string in Meta"
-MUTATION_CREATE_TOKEN = """
- mutation tokenCreate($email: String!, $password: String!){
- tokenCreate(email: $email, password: $password) {
- token
- user {
- email
- }
- errors {
- field
- message
- }
- accountErrors {
- field
- message
- code
- }
- }
- }
-"""
-
-
-def test_create_token(api_client, customer_user):
- variables = {"email": customer_user.email, "password": customer_user._password}
- response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
- content = get_graphql_content(response)
- user_email = content["data"]["tokenCreate"]["user"]["email"]
- assert customer_user.email == user_email
- assert content["data"]["tokenCreate"]["token"]
- assert content["data"]["tokenCreate"]["accountErrors"] == []
-
-
-def test_create_token_invalid_password(api_client, customer_user):
- variables = {"email": customer_user.email, "password": "wrongpassword"}
- expected_error_code = AccountErrorCode.INVALID_CREDENTIALS.value.upper()
- response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
- content = get_graphql_content(response)
- response_error = content["data"]["tokenCreate"]["accountErrors"][0]
- assert response_error["code"] == expected_error_code
- assert response_error["field"] == "email"
-
-
-def test_create_token_invalid_email(api_client, customer_user):
- variables = {"email": "wrongemail", "password": "wrongpassword"}
- expected_error_code = AccountErrorCode.INVALID_CREDENTIALS.value.upper()
- response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
- content = get_graphql_content(response)
- response_error = content["data"]["tokenCreate"]["accountErrors"][0]
- assert response_error["code"] == expected_error_code
- assert response_error["field"] == "email"
-
-
-MUTATION_TOKEN_VERIFY = """
- mutation tokenVerify($token: String!){
- tokenVerify(token: $token){
- user{
- email
- }
- }
- }
-"""
-
-
-def test_verify_token(api_client, customer_user):
- variables = {"token": get_token(customer_user)}
- response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)
- content = get_graphql_content(response)
- user_email = content["data"]["tokenVerify"]["user"]["email"]
- assert customer_user.email == user_email
-
-
-def test_verify_token_incorrect_token(api_client):
- variables = {"token": "incorrect_token"}
- response = api_client.post_graphql(MUTATION_TOKEN_VERIFY, variables)
- content = get_graphql_content(response)
- assert not content["data"]["tokenVerify"]
-
-
@pytest.mark.parametrize(
"cleaned_input",
[