Skip to content

Commit 1a79ec7

Browse files
[pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
1 parent 5a6c4cb commit 1a79ec7

17 files changed

+561
-552
lines changed

docs/cache_support.rst

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,3 @@ Cache keys follow this format:
6262

6363
- Refresh token: ``sjwt_brt:<jti>``
6464
- Token family: ``sjwt_btf:<family_id>``
65-

rest_framework_simplejwt/cache.py

Lines changed: 12 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
from django.core.cache import caches
2+
23
from .settings import api_settings
34

5+
46
class BlacklistCache:
57
"""
68
Cache implementation for Simple JWT blacklist functionalities.
79
Provides caching for both blacklisted refresh tokens and token families.
810
"""
9-
11+
1012
@property
1113
def cache(self):
1214
"""Get the configured cache backend for Simple JWT."""
1315
return caches[api_settings.SJWT_CACHE_NAME]
14-
16+
1517
@property
1618
def is_refresh_tokens_cache_enabled(self):
1719
"""Check if refresh token caching is enabled."""
1820
return api_settings.CACHE_BLACKLISTED_REFRESH_TOKENS
19-
21+
2022
@property
2123
def is_families_cache_enabled(self):
2224
"""Check if token family caching is enabled."""
@@ -29,39 +31,33 @@ def _get_refresh_token_key(self, jti: str) -> str:
2931
def _get_family_key(self, family_id: str) -> str:
3032
"""Generate cache key for a token family ID."""
3133
return f"{api_settings.CACHE_KEY_PREFIX_BLACKLISTED_FAMILIES}:{family_id}"
32-
34+
3335
def add_refresh_token(self, jti: str) -> None:
3436
"""Stores refresh token JTI in the cache."""
3537
key = self._get_refresh_token_key(jti)
3638
self.cache.set(
37-
key,
38-
True,
39-
timeout=api_settings.CACHE_TTL_BLACKLISTED_REFRESH_TOKENS
39+
key, True, timeout=api_settings.CACHE_TTL_BLACKLISTED_REFRESH_TOKENS
4040
)
41-
41+
4242
def is_refresh_token_blacklisted(self, jti: str) -> bool:
4343
"""Checks if a refresh token JTI is blacklisted in cache."""
4444
return self.cache.get(self._get_refresh_token_key(jti), False)
4545

4646
def add_token_family(self, family_id: str) -> None:
4747
"""Stores a token family ID in the cache."""
4848
key = self._get_family_key(family_id)
49-
self.cache.set(
50-
key,
51-
True,
52-
timeout=api_settings.CACHE_TTL_BLACKLISTED_FAMILIES
53-
)
49+
self.cache.set(key, True, timeout=api_settings.CACHE_TTL_BLACKLISTED_FAMILIES)
5450

5551
def is_token_family_blacklisted(self, family_id: str) -> bool:
5652
"""Checks if a token family is blacklisted in cache."""
57-
return self.cache.get(self._get_family_key(family_id), False)
58-
53+
return self.cache.get(self._get_family_key(family_id), False)
54+
5955
def delete_refresh_token_from_cache(self, jti: str) -> bool:
6056
"""Returns True if the token jti was successfully deleted, False otherwise."""
6157
return self.cache.delete(self._get_refresh_token_key(jti))
6258

6359
def delete_family_from_cache(self, family_id: str) -> bool:
64-
"""Returns True if the family ID was successfully deleted, False otherwise."""
60+
"""Returns True if the family ID was successfully deleted, False otherwise."""
6561
return self.cache.delete(self._get_family_key(family_id))
6662

6763

rest_framework_simplejwt/exceptions.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class TokenBackendExpiredToken(TokenBackendError):
2222

2323
class RefreshTokenBlacklistedError(TokenError):
2424
"""Raised when a refresh token is found in the blacklist."""
25+
2526
pass
2627

2728

@@ -66,4 +67,4 @@ class TokenFamilyNotConfigured(DetailDictMixin, exceptions.APIException):
6667
default_detail = _(
6768
"Token family functionality is not enabled or available. Please check your configuration."
6869
)
69-
default_code = "token_family_not_configured"
70+
default_code = "token_family_not_configured"

rest_framework_simplejwt/serializers.py

Lines changed: 19 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,16 @@
77
from rest_framework import exceptions, serializers
88
from rest_framework.exceptions import AuthenticationFailed, ValidationError
99

10-
from .exceptions import TokenError, TokenFamilyNotConfigured, RefreshTokenBlacklistedError
10+
from .cache import blacklist_cache
11+
from .exceptions import (
12+
RefreshTokenBlacklistedError,
13+
TokenError,
14+
TokenFamilyNotConfigured,
15+
)
1116
from .models import TokenUser
1217
from .settings import api_settings
13-
from .tokens import RefreshToken, SlidingToken, Token, UntypedToken, FamilyMixin
14-
from .cache import blacklist_cache
1518
from .token_blacklist.models import BlacklistedToken
19+
from .tokens import FamilyMixin, RefreshToken, SlidingToken, Token, UntypedToken
1620

1721
AuthUser = TypeVar("AuthUser", AbstractBaseUser, TokenUser)
1822

@@ -143,7 +147,7 @@ def validate(self, attrs: dict[str, Any]) -> dict[str, str]:
143147
data["refresh"] = str(refresh)
144148

145149
return data
146-
150+
147151
def _get_refresh_token(self, token_str: str) -> RefreshToken:
148152
"""
149153
Handles refresh token instantiation and family blacklisting if enabled.
@@ -152,9 +156,9 @@ def _get_refresh_token(self, token_str: str) -> RefreshToken:
152156
return self.token_class(token_str)
153157
except RefreshTokenBlacklistedError as e:
154158
if (
155-
api_settings.TOKEN_FAMILY_ENABLED and
156-
api_settings.TOKEN_FAMILY_BLACKLIST_ON_REUSE and
157-
"rest_framework_simplejwt.token_family" in settings.INSTALLED_APPS
159+
api_settings.TOKEN_FAMILY_ENABLED
160+
and api_settings.TOKEN_FAMILY_BLACKLIST_ON_REUSE
161+
and "rest_framework_simplejwt.token_family" in settings.INSTALLED_APPS
158162
):
159163
refresh = self.token_class(token=token_str, verify=False)
160164
family_id = refresh.get_family_id()
@@ -202,13 +206,13 @@ def validate(self, attrs: dict[str, None]) -> dict[Any, Any]:
202206

203207
if BlacklistedToken.objects.filter(token__jti=jti).exists():
204208
raise ValidationError(_("Token is blacklisted"))
205-
209+
206210
if (
207-
api_settings.TOKEN_FAMILY_ENABLED and
208-
"rest_framework_simplejwt.token_family" in settings.INSTALLED_APPS
209-
):
210-
FamilyMixin.check_family_expiration(token= token)
211-
FamilyMixin.check_family_blacklist(token= token)
211+
api_settings.TOKEN_FAMILY_ENABLED
212+
and "rest_framework_simplejwt.token_family" in settings.INSTALLED_APPS
213+
):
214+
FamilyMixin.check_family_expiration(token=token)
215+
FamilyMixin.check_family_blacklist(token=token)
212216

213217
return {}
214218

@@ -224,7 +228,7 @@ def validate(self, attrs: dict[str, Any]) -> dict[Any, Any]:
224228
except AttributeError:
225229
pass
226230
return {}
227-
231+
228232

229233
class TokenFamilyBlacklistSerializer(serializers.Serializer):
230234
refresh = serializers.CharField(write_only=True)
@@ -238,5 +242,5 @@ def validate(self, attrs: dict[str, Any]) -> dict[Any, Any]:
238242
raise TokenFamilyNotConfigured()
239243
except TokenError as e:
240244
raise serializers.ValidationError({"refresh": str(e)})
241-
245+
242246
return {"message": "Token Family blacklisted"}
Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,4 @@
11
from django import VERSION
22

33
if VERSION < (3, 2):
4-
default_app_config = (
5-
"rest_framework_simplejwt.token_family.apps.TokenFamilyConfig"
6-
)
4+
default_app_config = "rest_framework_simplejwt.token_family.apps.TokenFamilyConfig"

rest_framework_simplejwt/token_family/admin.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
from rest_framework.request import Request
99

1010
from ..models import TokenUser
11-
from .models import TokenFamily, BlacklistedTokenFamily
11+
from .models import BlacklistedTokenFamily, TokenFamily
1212

1313
AuthUser = TypeVar("AuthUser", AbstractBaseUser, TokenUser)
1414

@@ -98,4 +98,4 @@ def family_expires_at(self, obj: BlacklistedTokenFamily) -> datetime:
9898
family_expires_at.admin_order_field = "family__expires_at" # type: ignore
9999

100100

101-
admin.site.register(BlacklistedTokenFamily, BlacklistedTokenFamilyAdmin)
101+
admin.site.register(BlacklistedTokenFamily, BlacklistedTokenFamilyAdmin)

rest_framework_simplejwt/token_family/apps.py

Lines changed: 26 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
from datetime import timedelta
2+
13
from django.apps import AppConfig
2-
from django.utils.translation import gettext_lazy as _
34
from django.core.exceptions import ImproperlyConfigured
45
from django.utils.module_loading import import_string
5-
from datetime import timedelta
6+
from django.utils.translation import gettext_lazy as _
7+
68
from rest_framework_simplejwt.settings import api_settings
79

810

@@ -30,31 +32,45 @@ def _validate_family_settings() -> None:
3032

3133
family_exp_claim = api_settings.TOKEN_FAMILY_EXPIRATION_CLAIM
3234
if not isinstance(family_exp_claim, str) or not family_exp_claim.strip():
33-
raise ImproperlyConfigured("TOKEN_FAMILY_EXPIRATION_CLAIM must be a non-empty string")
35+
raise ImproperlyConfigured(
36+
"TOKEN_FAMILY_EXPIRATION_CLAIM must be a non-empty string"
37+
)
3438

3539
family_lifetime = api_settings.TOKEN_FAMILY_LIFETIME
3640
if family_lifetime is not None and not isinstance(family_lifetime, timedelta):
37-
raise ImproperlyConfigured("TOKEN_FAMILY_LIFETIME must be of type timedelta or None")
41+
raise ImproperlyConfigured(
42+
"TOKEN_FAMILY_LIFETIME must be of type timedelta or None"
43+
)
3844

3945
family_enabled = api_settings.TOKEN_FAMILY_ENABLED
4046
if not isinstance(family_enabled, bool):
4147
raise ImproperlyConfigured("TOKEN_FAMILY_ENABLED must be of type bool")
4248

4349
check_on_access = api_settings.TOKEN_FAMILY_CHECK_ON_ACCESS
4450
if not isinstance(check_on_access, bool):
45-
raise ImproperlyConfigured("TOKEN_FAMILY_CHECK_ON_ACCESS must be of type bool")
51+
raise ImproperlyConfigured(
52+
"TOKEN_FAMILY_CHECK_ON_ACCESS must be of type bool"
53+
)
4654

4755
blacklist_on_reuse = api_settings.TOKEN_FAMILY_BLACKLIST_ON_REUSE
4856
if not isinstance(blacklist_on_reuse, bool):
49-
raise ImproperlyConfigured("TOKEN_FAMILY_BLACKLIST_ON_REUSE must be of type bool")
50-
57+
raise ImproperlyConfigured(
58+
"TOKEN_FAMILY_BLACKLIST_ON_REUSE must be of type bool"
59+
)
5160

5261
# Validate TOKEN_FAMILY_BLACKLIST_SERIALIZER
5362
blacklist_serializer_path = api_settings.TOKEN_FAMILY_BLACKLIST_SERIALIZER
54-
if not isinstance(blacklist_serializer_path, str) or not blacklist_serializer_path.strip():
55-
raise ImproperlyConfigured("TOKEN_FAMILY_BLACKLIST_SERIALIZER must be a non-empty string")
63+
if (
64+
not isinstance(blacklist_serializer_path, str)
65+
or not blacklist_serializer_path.strip()
66+
):
67+
raise ImproperlyConfigured(
68+
"TOKEN_FAMILY_BLACKLIST_SERIALIZER must be a non-empty string"
69+
)
5670

5771
try:
5872
import_string(blacklist_serializer_path)
5973
except ImportError as e:
60-
raise ImportError(f"Could not import serializer '{blacklist_serializer_path}': {e}") from e
74+
raise ImportError(
75+
f"Could not import serializer '{blacklist_serializer_path}': {e}"
76+
) from e

rest_framework_simplejwt/token_family/migrations/0001_initial.py

Lines changed: 30 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66

77

88
class Migration(migrations.Migration):
9-
109
initial = True
1110

1211
dependencies = [
@@ -15,29 +14,45 @@ class Migration(migrations.Migration):
1514

1615
operations = [
1716
migrations.CreateModel(
18-
name='TokenFamily',
17+
name="TokenFamily",
1918
fields=[
20-
('id', models.BigAutoField(primary_key=True, serialize=False)),
21-
('family_id', models.CharField(max_length=255, unique=True)),
22-
('created_at', models.DateTimeField(blank=True)),
23-
('expires_at', models.DateTimeField(blank=True, null=True)),
24-
('user', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='token_families', to=settings.AUTH_USER_MODEL)),
19+
("id", models.BigAutoField(primary_key=True, serialize=False)),
20+
("family_id", models.CharField(max_length=255, unique=True)),
21+
("created_at", models.DateTimeField(blank=True)),
22+
("expires_at", models.DateTimeField(blank=True, null=True)),
23+
(
24+
"user",
25+
models.ForeignKey(
26+
blank=True,
27+
null=True,
28+
on_delete=django.db.models.deletion.SET_NULL,
29+
related_name="token_families",
30+
to=settings.AUTH_USER_MODEL,
31+
),
32+
),
2533
],
2634
options={
27-
'verbose_name': 'Token Family',
28-
'verbose_name_plural': 'Token Families',
35+
"verbose_name": "Token Family",
36+
"verbose_name_plural": "Token Families",
2937
},
3038
),
3139
migrations.CreateModel(
32-
name='TokenFamilyBlacklist',
40+
name="TokenFamilyBlacklist",
3341
fields=[
34-
('id', models.BigAutoField(primary_key=True, serialize=False)),
35-
('blacklisted_at', models.DateTimeField(auto_now_add=True)),
36-
('family', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='blacklisted', to='token_family.tokenfamily')),
42+
("id", models.BigAutoField(primary_key=True, serialize=False)),
43+
("blacklisted_at", models.DateTimeField(auto_now_add=True)),
44+
(
45+
"family",
46+
models.OneToOneField(
47+
on_delete=django.db.models.deletion.CASCADE,
48+
related_name="blacklisted",
49+
to="token_family.tokenfamily",
50+
),
51+
),
3752
],
3853
options={
39-
'verbose_name': 'Token Family Blacklist',
40-
'verbose_name_plural': 'Blacklisted Token Families',
54+
"verbose_name": "Token Family Blacklist",
55+
"verbose_name_plural": "Blacklisted Token Families",
4156
},
4257
),
4358
]

rest_framework_simplejwt/token_family/migrations/0002_rename_tokenfamilyblacklist_blacklistedtokenfamily.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,13 @@
44

55

66
class Migration(migrations.Migration):
7-
87
dependencies = [
9-
('token_family', '0001_initial'),
8+
("token_family", "0001_initial"),
109
]
1110

1211
operations = [
1312
migrations.RenameModel(
14-
old_name='TokenFamilyBlacklist',
15-
new_name='BlacklistedTokenFamily',
13+
old_name="TokenFamilyBlacklist",
14+
new_name="BlacklistedTokenFamily",
1615
),
1716
]

0 commit comments

Comments
 (0)