Skip to content

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

Add threshold when updating user.last_login field (#16245)

Maciej Korycinski74fbba6d0734
diff --git a/saleor/graphql/account/mutations/authentication/create_token.py b/saleor/graphql/account/mutations/authentication/create_token.py
index 394e3cafa7..497c3a5d18 100644
--- a/saleor/graphql/account/mutations/authentication/create_token.py
+++ b/saleor/graphql/account/mutations/authentication/create_token.py
@@ -1,6 +1,8 @@
+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
@@ -97,7 +99,6 @@ class CreateToken(BaseMutation):
def perform_mutation( # type: ignore[override]
cls, _root, info: ResolveInfo, /, *, audience=None, email, password
):
- user = cls.get_user(info, email, password)
additional_paylod = {}
csrf_token = _get_new_csrf_token()
@@ -108,6 +109,7 @@ class CreateToken(BaseMutation):
additional_paylod["aud"] = f"custom:{audience}"
refresh_additional_payload["aud"] = f"custom:{audience}"
+ user = cls.get_user(info, email, password)
access_token = create_access_token(user, additional_payload=additional_paylod)
refresh_token = create_refresh_token(
user, additional_payload=refresh_additional_payload
@@ -115,8 +117,12 @@ class CreateToken(BaseMutation):
setattr(info.context, "refresh_token", refresh_token)
info.context.user = user
info.context._cached_user = user
- user.last_login = timezone.now()
- user.save(update_fields=["last_login", "updated_at"])
+ 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"])
return cls(
errors=[],
user=user,
diff --git a/saleor/graphql/account/mutations/authentication/refresh_token.py b/saleor/graphql/account/mutations/authentication/refresh_token.py
index b461fffc36..ead95850c8 100644
--- a/saleor/graphql/account/mutations/authentication/refresh_token.py
+++ b/saleor/graphql/account/mutations/authentication/refresh_token.py
@@ -1,6 +1,8 @@
+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
@@ -128,12 +130,17 @@ class RefreshToken(BaseMutation):
if need_csrf:
cls.clean_csrf_token(csrf_token, payload)
- user = get_user(payload)
additional_payload = {}
if audience := payload.get("aud"):
additional_payload["aud"] = audience
+ user = get_user(payload)
token = create_access_token(user, additional_payload=additional_payload)
if user and not user.is_anonymous:
- user.last_login = timezone.now()
- user.save(update_fields=["last_login", "updated_at"])
+ 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"])
return cls(errors=[], user=user, token=token)
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 26512a00c9..3965da7244 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_create.py
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta, timezone
import graphene
+import pytz
from django.urls import reverse
from freezegun import freeze_time
@@ -284,3 +285,58 @@ def test_create_token_email_case_insensitive(api_client, customer_user, settings
assert customer_user.email == data["user"]["email"]
assert not data["errors"]
assert data["token"]
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_create_token_do_not_update_last_login_when_in_threshold(
+ api_client, customer_user, settings
+):
+ # given
+ customer_password = customer_user._password
+ 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
+ variables = {"email": customer_user.email, "password": customer_password}
+ 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_CREATE_TOKEN, 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
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_create_token_do_update_last_login_when_out_of_threshold(
+ api_client, customer_user, settings
+):
+ # given
+ customer_password = customer_user._password
+ 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
+
+ variables = {"email": customer_user.email, "password": customer_password}
+ 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_CREATE_TOKEN, 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_in_threshold
+ assert customer_user.last_login == time_in_threshold
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 f0baffa79d..35714dd83b 100644
--- a/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
+++ b/saleor/graphql/account/tests/mutations/authentication/test_token_refresh.py
@@ -1,6 +1,7 @@
-from datetime import datetime
+from datetime import datetime, timedelta
import pytest
+import pytz
from django.urls import reverse
from freezegun import freeze_time
@@ -292,3 +293,77 @@ def test_refresh_token_incorrect_token_provided(api_client, customer_user, token
assert not data.get("token")
assert len(errors) == 1
assert errors[0]["code"] == AccountErrorCode.JWT_DECODE_ERROR.name
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_token_do_not_update_last_login_when_in_threshold(
+ api_client, customer_user, settings
+):
+ # given
+ csrf_token = _get_new_csrf_token()
+ token_audience = "custom:dashboard"
+ refresh_token = create_refresh_token(
+ customer_user, {"csrfToken": csrf_token, "aud": token_audience}
+ )
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
+
+ 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
+
+ variables = {"token": None, "csrf_token": csrf_token}
+
+ 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_TOKEN_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
+
+
+@freeze_time("2020-03-18 12:00:00")
+def test_refresh_token_do_update_last_login_when_out_of_threshold(
+ api_client, customer_user, settings
+):
+ # given
+ csrf_token = _get_new_csrf_token()
+ token_audience = "custom:dashboard"
+ refresh_token = create_refresh_token(
+ customer_user, {"csrfToken": csrf_token, "aud": token_audience}
+ )
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME] = refresh_token
+ api_client.cookies[JWT_REFRESH_TOKEN_COOKIE_NAME]["httponly"] = True
+
+ 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
+
+ variables = {"token": None, "csrf_token": csrf_token}
+
+ 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_TOKEN_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_in_threshold
+ assert customer_user.last_login == time_in_threshold
diff --git a/saleor/settings.py b/saleor/settings.py
index 0c680c8c75..f33c48402d 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -916,6 +916,12 @@ OAUTH_UPDATE_LAST_LOGIN_THRESHOLD = parse(
os.environ.get("OAUTH_UPDATE_LAST_LOGIN_THRESHOLD", "15 minutes")
)
+# Time threshold to update user last_login when using tokenCreate/tokenRefresh
+# mutations.
+TOKEN_UPDATE_LAST_LOGIN_THRESHOLD = parse(
+ os.environ.get("TOKEN_UPDATE_LAST_LOGIN_THRESHOLD", "5 seconds")
+)
+
# Max lock time for checkout processing.
# It prevents locking checkout when unhandled issue appears.
CHECKOUT_COMPLETION_LOCK_TIME = parse(