Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add tests for checking the mutations to deactivate all tokens
Maciej Korycinski3f7658d31c1c
diff --git a/saleor/account/models.py b/saleor/account/models.pyindex 6d4dfd203f..80562fac32 100644--- a/saleor/account/models.py+++ b/saleor/account/models.py@@ -150,6 +150,7 @@ class User(PermissionsMixin, ModelWithMetadata, AbstractBaseUser):)avatar = VersatileImageField(upload_to="user-avatars", blank=True, null=True)jwt_token_key = models.CharField(max_length=12, default=get_random_string)+USERNAME_FIELD = "email"objects = UserManager()diff --git a/saleor/graphql/account/mutations/jwt.py b/saleor/graphql/account/mutations/jwt.pyindex c22a2cca44..48c40731ac 100644--- a/saleor/graphql/account/mutations/jwt.py+++ b/saleor/graphql/account/mutations/jwt.py@@ -4,6 +4,7 @@ from django.contrib.auth import authenticatefrom django.core.exceptions import ValidationErrorfrom django.middleware.csrf import _compare_salted_tokens, _get_new_csrf_tokenfrom django.utils import timezone+from django.utils.crypto import get_random_stringfrom graphene.types.generic import GenericScalarfrom ....account.error_codes import AccountErrorCode@@ -230,3 +231,21 @@ class VerifyToken(BaseMutation):payload = cls.get_payload(token)user = cls.get_user(payload)return cls(errors=[], user=user, is_valid=True, payload=payload)+++class DeactivateAllUserTokens(BaseMutation):+ class Meta:+ description = "Deactivate all existing JWT tokens assigned to user."+ error_type_class = AccountError+ error_type_field = "account_errors"++ @classmethod+ def check_permissions(cls, context):+ return context.user.is_authenticated++ @classmethod+ def perform_mutation(cls, root, info, **data):+ user = info.context.user+ user.jwt_token_key = get_random_string()+ user.save()+ return cls()diff --git a/saleor/graphql/account/schema.py b/saleor/graphql/account/schema.pyindex aa97faf63f..3b54c381e5 100644--- a/saleor/graphql/account/schema.py+++ b/saleor/graphql/account/schema.py@@ -40,7 +40,12 @@ from .mutations.base import (UserClearMeta,UserUpdateMeta,)-from .mutations.jwt import CreateToken, RefreshToken, VerifyToken+from .mutations.jwt import (+ CreateToken,+ DeactivateAllUserTokens,+ RefreshToken,+ VerifyToken,+)from .mutations.permission_group import (PermissionGroupCreate,PermissionGroupDelete,@@ -223,6 +228,7 @@ class AccountMutations(graphene.ObjectType):token_create = CreateToken.Field()token_refresh = RefreshToken.Field()token_verify = VerifyToken.Field()+ tokens_deactivate_all = DeactivateAllUserTokens.Field()request_password_reset = RequestPasswordReset.Field()confirm_account = ConfirmAccount.Field()diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 3135f97197..ff743eea6a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -1541,6 +1541,11 @@ input DateTimeRangeInput {lte: DateTime}+type DeactivateAllUserTokens {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ accountErrors: [AccountError!]!+}+scalar Decimaltype DeleteMetadata {@@ -2476,6 +2481,7 @@ type Mutation {tokenCreate(email: String!, password: String!): CreateTokentokenRefresh(csrfToken: String!, refreshToken: String): RefreshTokentokenVerify(token: String!): VerifyToken+ tokensDeactivateAll: DeactivateAllUserTokensrequestPasswordReset(email: String!, redirectUrl: String!): RequestPasswordResetconfirmAccount(email: String!, token: String!): ConfirmAccountsetPassword(email: String!, password: String!, token: String!): SetPassworddiff --git a/tests/api/test_account_mutations_jwt.py b/tests/api/test_account_mutations_jwt.pyindex 726d5432c7..310e29ee86 100644--- a/tests/api/test_account_mutations_jwt.py+++ b/tests/api/test_account_mutations_jwt.py@@ -14,6 +14,7 @@ from saleor.core.jwt import (JWT_SECRET,create_access_token,create_refresh_token,+ jwt_decode,)from tests.api.utils import get_graphql_content@@ -337,7 +338,6 @@ def test_refresh_token_when_user_deactivated_token(api_client, customer_user):response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)content = get_graphql_content(response)- print(content)data = content["data"]["tokenRefresh"]errors = data["accountErrors"]@@ -345,3 +345,79 @@ def test_refresh_token_when_user_deactivated_token(api_client, customer_user):assert not data["token"]assert len(errors) == 1assert errors[0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.name+++MUTATION_DEACTIVATE_ALL_USER_TOKENS = """+mutation{+ tokensDeactivateAll{+ accountErrors{+ field+ message+ code+ }+ }+}++"""+++@freeze_time("2020-03-18 12:00:00")+def test_deactivate_all_user_tokens(customer_user, user_api_client):+ token = create_access_token(customer_user)+ jwt_key = customer_user.jwt_token_key++ csrf_token = _get_new_csrf_token()+ refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})++ user_api_client.token = token+ user_api_client.post_graphql(MUTATION_DEACTIVATE_ALL_USER_TOKENS)+ customer_user.refresh_from_db()++ new_token = create_access_token(customer_user)+ new_refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})+ # the mutation changes the parameter of jwt token, which confirms if jwt token is+ # valid or not+ assert jwt_decode(token)["token"] != jwt_decode(new_token)["token"]+ assert jwt_decode(refresh_token)["token"] != jwt_decode(new_refresh_token)["token"]+ assert jwt_key != customer_user.jwt_token_key+++def test_deactivate_all_user_tokens_access_token(user_api_client, customer_user):+ token = create_access_token(customer_user)+ user_api_client.token = token+ response = user_api_client.post_graphql(MUTATION_DEACTIVATE_ALL_USER_TOKENS)+ content = get_graphql_content(response)++ errors = content["data"]["tokensDeactivateAll"]["accountErrors"]+ assert not errors++ query = "{me { id }}"+ response = user_api_client.post_graphql(query)+ content = get_graphql_content(response)+ assert content["data"]["me"] is None+++def test_deactivate_all_user_token_refresh_token(+ api_client, user_api_client, customer_user+):+ user_api_client.token = create_access_token(customer_user)+ create_refresh_token(customer_user)+ csrf_token = _get_new_csrf_token()+ refresh_token = create_refresh_token(customer_user, {"csrfToken": csrf_token})++ response = user_api_client.post_graphql(MUTATION_DEACTIVATE_ALL_USER_TOKENS)+ content = get_graphql_content(response)+ errors = content["data"]["tokensDeactivateAll"]["accountErrors"]+ assert not errors++ variables = {"token": refresh_token, "csrf_token": csrf_token}+ response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)+ content = get_graphql_content(response)++ data = content["data"]["tokenRefresh"]+ errors = data["accountErrors"]++ assert data["token"] is None+ assert len(errors) == 1++ assert errors[0]["code"] == AccountErrorCode.JWT_INVALID_TOKEN.name