Skip to content

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

Use last-login treshold in external mutations (#16248)

Maciej Korycinskie8a888924e9e
diff --git a/saleor/graphql/account/mutations/authentication/create_token.py b/saleor/graphql/account/mutations/authentication/create_token.py
index 40a1132be5..a600aa1262 100644
--- a/saleor/graphql/account/mutations/authentication/create_token.py
+++ b/saleor/graphql/account/mutations/authentication/create_token.py
@@ -1,9 +1,5 @@
-from datetime import timedelta
-
import graphene
-from django.conf import settings
from django.core.exceptions import ValidationError
-from django.utils import timezone
from .....account.error_codes import AccountErrorCode
from .....account.throttling import authenticate_with_throttling
@@ -15,7 +11,7 @@ from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....site.dataloaders import get_site_promise
from ...types import User
-from .utils import _get_new_csrf_token
+from .utils import _get_new_csrf_token, update_user_last_login_if_required
class CreateToken(BaseMutation):
@@ -108,12 +104,7 @@ class CreateToken(BaseMutation):
setattr(info.context, "refresh_token", refresh_token)
info.context.user = user
info.context._cached_user = user
- time_now = timezone.now()
- threshold_delta = timedelta(seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD)
-
- if not user.last_login or user.last_login + threshold_delta < time_now:
- user.last_login = time_now
- user.save(update_fields=["last_login", "updated_at"])
+ update_user_last_login_if_required(user)
return cls(
errors=[],
user=user,
diff --git a/saleor/graphql/account/mutations/authentication/external_obtain_access_tokens.py b/saleor/graphql/account/mutations/authentication/external_obtain_access_tokens.py
index 618f6da826..9b3fe25697 100644
--- a/saleor/graphql/account/mutations/authentication/external_obtain_access_tokens.py
+++ b/saleor/graphql/account/mutations/authentication/external_obtain_access_tokens.py
@@ -1,5 +1,4 @@
import graphene
-from django.utils import timezone
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_AUTH
@@ -8,6 +7,7 @@ from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import User
+from .utils import update_user_last_login_if_required
class ExternalObtainAccessTokens(BaseMutation):
@@ -49,9 +49,9 @@ class ExternalObtainAccessTokens(BaseMutation):
setattr(info.context, "refresh_token", access_tokens_response.refresh_token)
if access_tokens_response.user and access_tokens_response.user.id:
- info.context._cached_user = access_tokens_response.user
- access_tokens_response.user.last_login = timezone.now()
- access_tokens_response.user.save(update_fields=["last_login", "updated_at"])
+ user = access_tokens_response.user
+ info.context._cached_user = user
+ update_user_last_login_if_required(user)
return cls(
token=access_tokens_response.token,
diff --git a/saleor/graphql/account/mutations/authentication/external_refresh.py b/saleor/graphql/account/mutations/authentication/external_refresh.py
index f378b37d34..85d2900cb4 100644
--- a/saleor/graphql/account/mutations/authentication/external_refresh.py
+++ b/saleor/graphql/account/mutations/authentication/external_refresh.py
@@ -1,5 +1,4 @@
import graphene
-from django.utils import timezone
from ....core import ResolveInfo
from ....core.doc_category import DOC_CATEGORY_AUTH
@@ -8,6 +7,7 @@ from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ....plugins.dataloaders import get_plugin_manager_promise
from ...types import User
+from .utils import update_user_last_login_if_required
class ExternalRefresh(BaseMutation):
@@ -47,9 +47,9 @@ class ExternalRefresh(BaseMutation):
setattr(info.context, "refresh_token", access_tokens_response.refresh_token)
if access_tokens_response.user and access_tokens_response.user.id:
- info.context._cached_user = access_tokens_response.user
- access_tokens_response.user.last_login = timezone.now()
- access_tokens_response.user.save(update_fields=["last_login", "updated_at"])
+ user = access_tokens_response.user
+ info.context._cached_user = user
+ update_user_last_login_if_required(user)
return cls(
token=access_tokens_response.token,
diff --git a/saleor/graphql/account/mutations/authentication/refresh_token.py b/saleor/graphql/account/mutations/authentication/refresh_token.py
index ead95850c8..9807e79fe0 100644
--- a/saleor/graphql/account/mutations/authentication/refresh_token.py
+++ b/saleor/graphql/account/mutations/authentication/refresh_token.py
@@ -1,10 +1,7 @@
-from datetime import timedelta
from typing import Optional
import graphene
-from django.conf import settings
from django.core.exceptions import ValidationError
-from django.utils import timezone
from .....account.error_codes import AccountErrorCode
from .....core.jwt import (
@@ -17,7 +14,12 @@ from ....core.doc_category import DOC_CATEGORY_AUTH
from ....core.mutations import BaseMutation
from ....core.types import AccountError
from ...types import User
-from .utils import _does_token_match, get_payload, get_user
+from .utils import (
+ _does_token_match,
+ get_payload,
+ get_user,
+ update_user_last_login_if_required,
+)
class RefreshToken(BaseMutation):
@@ -136,11 +138,5 @@ class RefreshToken(BaseMutation):
user = get_user(payload)
token = create_access_token(user, additional_payload=additional_payload)
if user and not user.is_anonymous:
- time_now = timezone.now()
- threshold_delta = timedelta(
- seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD
- )
- if not user.last_login or user.last_login + threshold_delta < time_now:
- user.last_login = time_now
- user.save(update_fields=["last_login", "updated_at"])
+ update_user_last_login_if_required(user)
return cls(errors=[], user=user, token=token)
diff --git a/saleor/graphql/account/mutations/authentication/utils.py b/saleor/graphql/account/mutations/authentication/utils.py
index 7ebfaef940..05f7de5948 100644
--- a/saleor/graphql/account/mutations/authentication/utils.py
+++ b/saleor/graphql/account/mutations/authentication/utils.py
@@ -1,13 +1,18 @@
+from datetime import timedelta
+
import jwt
+from django.conf import settings
from django.core.exceptions import ValidationError
from django.middleware.csrf import ( # type: ignore
_get_new_csrf_string,
_mask_cipher_secret,
_unmask_cipher_token,
)
+from django.utils import timezone
from django.utils.crypto import constant_time_compare
from .....account.error_codes import AccountErrorCode
+from .....account.models import User
from .....core.jwt import PERMISSIONS_FIELD, get_user_from_payload, jwt_decode
from .....permission.enums import get_permissions_from_names
@@ -54,3 +59,12 @@ def _does_token_match(token: str, csrf_token: str) -> bool:
_unmask_cipher_token(token),
_unmask_cipher_token(csrf_token),
)
+
+
+def update_user_last_login_if_required(user: User):
+ time_now = timezone.now()
+ threshold_delta = timedelta(seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD)
+
+ if not user.last_login or user.last_login + threshold_delta < time_now:
+ user.last_login = time_now
+ user.save(update_fields=["last_login", "updated_at"])
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py b/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py
index 21912ff98c..d28bdc6afa 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_external_obtain_access_tokens.py
@@ -1,6 +1,10 @@
import json
+from datetime import datetime, timedelta
from unittest.mock import Mock, patch
+import pytz
+from freezegun import freeze_time
+
from ......plugins.base_plugin import ExternalAccessTokens
from .....tests.utils import get_graphql_content
@@ -68,3 +72,97 @@ def test_external_obtain_access_tokens(
assert data["user"]["email"] == customer_user.email
assert mocked_plugin_fun.called
assert mock_refresh_token_middleware.called
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.core.middleware.jwt_decode_with_exception_handler")
+def test_external_obtain_access_tokens_do_not_update_last_login_when_in_threshold(
+ mock_refresh_token_middleware, api_client, customer_user, monkeypatch, settings
+):
+ # given
+ expected_token = "token1"
+ expected_refresh_token = "refresh2"
+ expected_csrf_token = "csrf3"
+ mocked_plugin_fun = Mock()
+ expected_return = ExternalAccessTokens(
+ token=expected_token,
+ refresh_token=expected_refresh_token,
+ csrf_token=expected_csrf_token,
+ user=customer_user,
+ )
+ mocked_plugin_fun.return_value = expected_return
+ monkeypatch.setattr(
+ "saleor.plugins.manager.PluginsManager.external_obtain_access_tokens",
+ mocked_plugin_fun,
+ )
+ variables = {
+ "pluginId": "pluginId1",
+ "input": json.dumps({"code": "ABCD", "state": "stata-data"}),
+ }
+ customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.save()
+ expected_last_login = customer_user.last_login
+ expected_updated_at = customer_user.updated_at
+
+ time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD - 1
+ )
+
+ # when
+ with freeze_time(time_in_threshold):
+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)
+
+ # then
+ get_graphql_content(response)
+ customer_user.refresh_from_db()
+ assert customer_user.updated_at == expected_updated_at
+ assert customer_user.last_login == expected_last_login
+ assert mock_refresh_token_middleware.called
+
+
+@freeze_time("2020-03-18 12:00:00")
+@patch("saleor.core.middleware.jwt_decode_with_exception_handler")
+def test_external_obtain_access_tokens_do_update_last_login_when_out_of_threshold(
+ mock_refresh_token_middleware, api_client, customer_user, monkeypatch, settings
+):
+ # given
+ expected_token = "token1"
+ expected_refresh_token = "refresh2"
+ expected_csrf_token = "csrf3"
+ mocked_plugin_fun = Mock()
+ expected_return = ExternalAccessTokens(
+ token=expected_token,
+ refresh_token=expected_refresh_token,
+ csrf_token=expected_csrf_token,
+ user=customer_user,
+ )
+ mocked_plugin_fun.return_value = expected_return
+ monkeypatch.setattr(
+ "saleor.plugins.manager.PluginsManager.external_obtain_access_tokens",
+ mocked_plugin_fun,
+ )
+ variables = {
+ "pluginId": "pluginId1",
+ "input": json.dumps({"code": "ABCD", "state": "stata-data"}),
+ }
+ customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.save()
+ previous_last_login = customer_user.last_login
+ previous_updated_at = customer_user.updated_at
+
+ time_out_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
+ )
+
+ # when
+ with freeze_time(time_out_of_threshold):
+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)
+
+ # then
+ get_graphql_content(response)
+ customer_user.refresh_from_db()
+ assert customer_user.updated_at != previous_updated_at
+ assert customer_user.last_login != previous_last_login
+ assert customer_user.updated_at == time_out_of_threshold
+ assert customer_user.last_login == time_out_of_threshold
+ assert mock_refresh_token_middleware.called
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py b/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py
index 320e6956ac..5163d4141a 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_external_refresh.py
@@ -1,6 +1,8 @@
import json
+from datetime import datetime, timedelta
from unittest.mock import Mock, patch
+import pytz
from freezegun import freeze_time
from ......plugins.base_plugin import ExternalAccessTokens
@@ -67,3 +69,91 @@ def test_external_refresh(
assert last_login == "2018-05-31 12:00:00"
assert mocked_plugin_fun.called
assert mock_refresh_token_middleware.called
+
+
+@freeze_time("2018-05-31 12:00:00")
+@patch("saleor.core.middleware.jwt_decode_with_exception_handler")
+def test_external_refresh_do_not_update_last_login_when_in_threshold(
+ mock_refresh_token_middleware, api_client, customer_user, monkeypatch, rf, settings
+):
+ # given
+ expected_token = "token1"
+ expected_refresh_token = "refresh2"
+ expected_csrf_token = "csrf3"
+ mocked_plugin_fun = Mock()
+ expected_return = ExternalAccessTokens(
+ token=expected_token,
+ refresh_token=expected_refresh_token,
+ csrf_token=expected_csrf_token,
+ user=customer_user,
+ )
+ mocked_plugin_fun.return_value = expected_return
+ monkeypatch.setattr(
+ "saleor.plugins.manager.PluginsManager.external_refresh", mocked_plugin_fun
+ )
+ variables = {"pluginId": "pluginId1", "input": json.dumps({"refreshToken": "ABCD"})}
+
+ customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.save()
+ expected_last_login = customer_user.last_login
+ expected_updated_at = customer_user.updated_at
+
+ time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD - 1
+ )
+
+ # when
+ with freeze_time(time_in_threshold):
+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)
+
+ # then
+ get_graphql_content(response)
+ customer_user.refresh_from_db()
+ assert customer_user.updated_at == expected_updated_at
+ assert customer_user.last_login == expected_last_login
+ assert mock_refresh_token_middleware.called
+
+
+@freeze_time("2018-05-31 12:00:00")
+@patch("saleor.core.middleware.jwt_decode_with_exception_handler")
+def test_external_refresh_do_update_last_login_when_out_of_threshold(
+ mock_refresh_token_middleware, api_client, customer_user, monkeypatch, rf, settings
+):
+ # given
+ expected_token = "token1"
+ expected_refresh_token = "refresh2"
+ expected_csrf_token = "csrf3"
+ mocked_plugin_fun = Mock()
+ expected_return = ExternalAccessTokens(
+ token=expected_token,
+ refresh_token=expected_refresh_token,
+ csrf_token=expected_csrf_token,
+ user=customer_user,
+ )
+ mocked_plugin_fun.return_value = expected_return
+ monkeypatch.setattr(
+ "saleor.plugins.manager.PluginsManager.external_refresh", mocked_plugin_fun
+ )
+ variables = {"pluginId": "pluginId1", "input": json.dumps({"refreshToken": "ABCD"})}
+
+ customer_user.last_login = datetime.now(tz=pytz.UTC)
+ customer_user.save()
+ previous_last_login = customer_user.last_login
+ previous_updated_at = customer_user.updated_at
+
+ time_out_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
+ )
+
+ # when
+ with freeze_time(time_out_of_threshold):
+ response = api_client.post_graphql(MUTATION_EXTERNAL_REFRESH, variables)
+
+ # then
+ get_graphql_content(response)
+ customer_user.refresh_from_db()
+ assert customer_user.updated_at != previous_updated_at
+ assert customer_user.last_login != previous_last_login
+ assert customer_user.updated_at == time_out_of_threshold
+ assert customer_user.last_login == time_out_of_threshold
+ assert mock_refresh_token_middleware.called
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
index 4d73a676c6..1ffc22781d 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
@@ -378,12 +378,12 @@ def test_create_token_do_update_last_login_when_out_of_threshold(
previous_updated_at = customer_user.updated_at
variables = {"email": customer_user.email, "password": customer_password}
- time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_out_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
)
# when
- with freeze_time(time_in_threshold):
+ with freeze_time(time_out_of_threshold):
response = api_client.post_graphql(MUTATION_CREATE_TOKEN, variables)
# then
@@ -391,8 +391,8 @@ def test_create_token_do_update_last_login_when_out_of_threshold(
customer_user.refresh_from_db()
assert customer_user.updated_at != previous_updated_at
assert customer_user.last_login != previous_last_login
- assert customer_user.updated_at == time_in_threshold
- assert customer_user.last_login == time_in_threshold
+ assert customer_user.updated_at == time_out_of_threshold
+ assert customer_user.last_login == time_out_of_threshold
@freeze_time("2020-03-18 12:00:00")
diff --git a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
index 35714dd83b..cd200ee0fd 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
@@ -352,12 +352,12 @@ def test_refresh_token_do_update_last_login_when_out_of_threshold(
variables = {"token": None, "csrf_token": csrf_token}
- time_in_threshold = datetime.now(tz=pytz.UTC) + timedelta(
+ time_ouf_of_threshold = datetime.now(tz=pytz.UTC) + timedelta(
seconds=settings.TOKEN_UPDATE_LAST_LOGIN_THRESHOLD + 1
)
# when
- with freeze_time(time_in_threshold):
+ with freeze_time(time_ouf_of_threshold):
response = api_client.post_graphql(MUTATION_TOKEN_REFRESH, variables)
# then
@@ -365,5 +365,5 @@ def test_refresh_token_do_update_last_login_when_out_of_threshold(
customer_user.refresh_from_db()
assert customer_user.updated_at != previous_updated_at
assert customer_user.last_login != previous_last_login
- assert customer_user.updated_at == time_in_threshold
- assert customer_user.last_login == time_in_threshold
+ assert customer_user.updated_at == time_ouf_of_threshold
+ assert customer_user.last_login == time_ouf_of_threshold