jwtninja 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jwtninja-0.1.0/PKG-INFO +15 -0
- jwtninja-0.1.0/README.md +3 -0
- jwtninja-0.1.0/jwt_ninja/__init__.py +0 -0
- jwtninja-0.1.0/jwt_ninja/admin.py +26 -0
- jwtninja-0.1.0/jwt_ninja/api.py +163 -0
- jwtninja-0.1.0/jwt_ninja/auth_classes.py +55 -0
- jwtninja-0.1.0/jwt_ninja/authenticators.py +12 -0
- jwtninja-0.1.0/jwt_ninja/cryptography.py +60 -0
- jwtninja-0.1.0/jwt_ninja/errors.py +70 -0
- jwtninja-0.1.0/jwt_ninja/handlers.py +10 -0
- jwtninja-0.1.0/jwt_ninja/migrations/0001_initial.py +37 -0
- jwtninja-0.1.0/jwt_ninja/migrations/__init__.py +0 -0
- jwtninja-0.1.0/jwt_ninja/models.py +102 -0
- jwtninja-0.1.0/jwt_ninja/request.py +18 -0
- jwtninja-0.1.0/jwt_ninja/settings.py +38 -0
- jwtninja-0.1.0/jwt_ninja/tests/__init__.py +0 -0
- jwtninja-0.1.0/jwt_ninja/tests/conftest.py +117 -0
- jwtninja-0.1.0/jwt_ninja/tests/django_settings.py +12 -0
- jwtninja-0.1.0/jwt_ninja/tests/test_api_endpoints.py +235 -0
- jwtninja-0.1.0/jwt_ninja/tests/test_jwt_auth.py +129 -0
- jwtninja-0.1.0/jwt_ninja/types.py +46 -0
- jwtninja-0.1.0/jwtninja.egg-info/PKG-INFO +15 -0
- jwtninja-0.1.0/jwtninja.egg-info/SOURCES.txt +26 -0
- jwtninja-0.1.0/jwtninja.egg-info/dependency_links.txt +1 -0
- jwtninja-0.1.0/jwtninja.egg-info/requires.txt +5 -0
- jwtninja-0.1.0/jwtninja.egg-info/top_level.txt +1 -0
- jwtninja-0.1.0/pyproject.toml +32 -0
- jwtninja-0.1.0/setup.cfg +4 -0
jwtninja-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: jwtninja
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: pydantic>=2.9.2
|
|
8
|
+
Requires-Dist: pydantic-settings>=2.5.2
|
|
9
|
+
Requires-Dist: uuid6>=2024.7.10
|
|
10
|
+
Requires-Dist: pyjwt>=2.9.0
|
|
11
|
+
Requires-Dist: django-ninja>=1.3.0
|
|
12
|
+
|
|
13
|
+
# JWT Ninja
|
|
14
|
+
|
|
15
|
+
A simple and fully-typed auth library for Django Ninja based on PyJWT.
|
jwtninja-0.1.0/README.md
ADDED
|
File without changes
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from django.contrib import admin
|
|
2
|
+
|
|
3
|
+
from .models import Session
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
@admin.register(Session)
|
|
7
|
+
class SessionAdmin(admin.ModelAdmin):
|
|
8
|
+
list_display = [
|
|
9
|
+
"id",
|
|
10
|
+
"user",
|
|
11
|
+
"created_at",
|
|
12
|
+
"updated_at",
|
|
13
|
+
"expired_at",
|
|
14
|
+
"ip_address",
|
|
15
|
+
]
|
|
16
|
+
readonly_fields = [
|
|
17
|
+
"id",
|
|
18
|
+
"user",
|
|
19
|
+
"created_at",
|
|
20
|
+
"updated_at",
|
|
21
|
+
"expired_at",
|
|
22
|
+
"ip_address",
|
|
23
|
+
"data",
|
|
24
|
+
]
|
|
25
|
+
list_filter = ["created_at", "expired_at"]
|
|
26
|
+
ordering = ["-id"]
|
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Any, Literal
|
|
3
|
+
|
|
4
|
+
from django.http import HttpRequest
|
|
5
|
+
from django.utils import timezone
|
|
6
|
+
from django.utils.module_loading import import_string
|
|
7
|
+
from ninja import Router
|
|
8
|
+
|
|
9
|
+
from .auth_classes import AuthedRequest, JWTAuth, User
|
|
10
|
+
from .cryptography import decode_jwt, generate_jwt
|
|
11
|
+
from .errors import (
|
|
12
|
+
APIError,
|
|
13
|
+
JWTExpiredError,
|
|
14
|
+
JWTInvalidPayloadFormat,
|
|
15
|
+
JWTInvalidTokenError,
|
|
16
|
+
)
|
|
17
|
+
from .models import Session
|
|
18
|
+
from .request import get_client_ip
|
|
19
|
+
from .settings import jwt_settings
|
|
20
|
+
from .types import (
|
|
21
|
+
AccessTokenSchema,
|
|
22
|
+
ErrorResponseType,
|
|
23
|
+
JWTPayload,
|
|
24
|
+
LoginSchema,
|
|
25
|
+
RefreshTokenSchema,
|
|
26
|
+
SessionResponse,
|
|
27
|
+
TokenSchema,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
router = Router(tags=["Authentication"])
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@router.post(
|
|
34
|
+
"login/",
|
|
35
|
+
summary="Obtain a new access token",
|
|
36
|
+
description="Supply a valid `username` and `password` to obtain a new `access_token` and `refresh_token`.",
|
|
37
|
+
response={
|
|
38
|
+
200: TokenSchema,
|
|
39
|
+
401: ErrorResponseType[Literal["invalid_credentials"]],
|
|
40
|
+
},
|
|
41
|
+
auth=None,
|
|
42
|
+
)
|
|
43
|
+
def login(request: HttpRequest, payload: LoginSchema) -> TokenSchema:
|
|
44
|
+
user = import_string(jwt_settings.USER_LOGIN_AUTHENTICATOR)(request, payload)
|
|
45
|
+
|
|
46
|
+
if not user:
|
|
47
|
+
raise APIError("invalid_credentials", 401)
|
|
48
|
+
|
|
49
|
+
# Create a new DB-backed session for the User
|
|
50
|
+
session = Session.create_session(
|
|
51
|
+
user=user,
|
|
52
|
+
ip_address=get_client_ip(request),
|
|
53
|
+
)
|
|
54
|
+
|
|
55
|
+
current_timestamp = int(time.time())
|
|
56
|
+
access_payload = JWTPayload(
|
|
57
|
+
user_id=user.id,
|
|
58
|
+
type="access",
|
|
59
|
+
# RFC 7519 says that the exp must be a NumericDate
|
|
60
|
+
# see https://www.rfc-editor.org/rfc/rfc7519#section-4.1.4
|
|
61
|
+
exp=current_timestamp + jwt_settings.ACCESS_TOKEN_EXPIRE_SECONDS,
|
|
62
|
+
session_id=session.id,
|
|
63
|
+
)
|
|
64
|
+
access_token = generate_jwt(access_payload)
|
|
65
|
+
|
|
66
|
+
refresh_payload = JWTPayload(
|
|
67
|
+
user_id=user.id,
|
|
68
|
+
exp=current_timestamp + jwt_settings.REFRESH_TOKEN_EXPIRE_SECONDS,
|
|
69
|
+
type="refresh",
|
|
70
|
+
session_id=session.id,
|
|
71
|
+
)
|
|
72
|
+
refresh_token = generate_jwt(refresh_payload)
|
|
73
|
+
|
|
74
|
+
return TokenSchema(access_token=access_token, refresh_token=refresh_token)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@router.post(
|
|
78
|
+
"refresh/",
|
|
79
|
+
summary="Refresh an access token",
|
|
80
|
+
description="Supply a valid, unexpired `refresh_token` to obtain a new `access_token`.",
|
|
81
|
+
response={
|
|
82
|
+
200: AccessTokenSchema,
|
|
83
|
+
400: ErrorResponseType[Literal["invalid_token_type"]],
|
|
84
|
+
401: ErrorResponseType[
|
|
85
|
+
Literal[
|
|
86
|
+
"token_expired",
|
|
87
|
+
"invalid_token",
|
|
88
|
+
"invalid_user",
|
|
89
|
+
]
|
|
90
|
+
],
|
|
91
|
+
},
|
|
92
|
+
auth=None,
|
|
93
|
+
)
|
|
94
|
+
def new_refresh_token(request: HttpRequest, payload: RefreshTokenSchema) -> Any:
|
|
95
|
+
try:
|
|
96
|
+
refresh_payload = decode_jwt(payload.refresh_token, JWTPayload)
|
|
97
|
+
except JWTExpiredError:
|
|
98
|
+
raise APIError("expired_token", http_status_code=401)
|
|
99
|
+
except (JWTInvalidTokenError, JWTInvalidPayloadFormat):
|
|
100
|
+
raise APIError("invalid_token", http_status_code=401)
|
|
101
|
+
|
|
102
|
+
if refresh_payload.type != "refresh":
|
|
103
|
+
raise APIError("invalid_token_type", http_status_code=400)
|
|
104
|
+
|
|
105
|
+
try:
|
|
106
|
+
user = User.objects.get(id=refresh_payload.user_id, is_active=True)
|
|
107
|
+
except User.DoesNotExist:
|
|
108
|
+
raise APIError("invalid_user", http_status_code=401)
|
|
109
|
+
|
|
110
|
+
current_timestamp = int(time.time())
|
|
111
|
+
access_payload = JWTPayload(
|
|
112
|
+
user_id=user.id,
|
|
113
|
+
exp=current_timestamp + jwt_settings.ACCESS_TOKEN_EXPIRE_SECONDS,
|
|
114
|
+
type="access",
|
|
115
|
+
session_id=refresh_payload.session_id,
|
|
116
|
+
)
|
|
117
|
+
try:
|
|
118
|
+
access_token = generate_jwt(access_payload)
|
|
119
|
+
except (JWTExpiredError, JWTInvalidTokenError, JWTInvalidPayloadFormat):
|
|
120
|
+
raise APIError("invalid_token", http_status_code=401)
|
|
121
|
+
|
|
122
|
+
return AccessTokenSchema(access_token=access_token)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@router.get(
|
|
126
|
+
"sessions/",
|
|
127
|
+
summary="List active sessions",
|
|
128
|
+
response={200: list[SessionResponse]},
|
|
129
|
+
auth=JWTAuth(),
|
|
130
|
+
)
|
|
131
|
+
def list_active_sessions(request: AuthedRequest):
|
|
132
|
+
return request.auth.user.jwt_sessions.filter(expired_at__isnull=True)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@router.post(
|
|
136
|
+
"logout/",
|
|
137
|
+
summary="Logout",
|
|
138
|
+
description="Log out of the current session.",
|
|
139
|
+
response={200: None},
|
|
140
|
+
auth=JWTAuth(),
|
|
141
|
+
)
|
|
142
|
+
def logout(request: AuthedRequest):
|
|
143
|
+
request.auth.session.expired_at = timezone.now()
|
|
144
|
+
request.auth.session.save()
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
@router.post(
|
|
149
|
+
"logout/all/",
|
|
150
|
+
summary="Logout from all sessions",
|
|
151
|
+
description="Log out of all sessions.",
|
|
152
|
+
response={200: None},
|
|
153
|
+
auth=JWTAuth(),
|
|
154
|
+
)
|
|
155
|
+
def logout_all(request: AuthedRequest):
|
|
156
|
+
# Sign out all active sessions
|
|
157
|
+
Session.objects.filter(
|
|
158
|
+
user_id=request.auth.user.id,
|
|
159
|
+
expired_at__isnull=True,
|
|
160
|
+
).update(
|
|
161
|
+
expired_at=timezone.now(),
|
|
162
|
+
)
|
|
163
|
+
return None
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import dataclasses
|
|
2
|
+
|
|
3
|
+
from django.contrib.auth import get_user_model
|
|
4
|
+
from django.http import HttpRequest
|
|
5
|
+
from django.utils import timezone
|
|
6
|
+
from ninja.security import HttpBearer
|
|
7
|
+
|
|
8
|
+
from .cryptography import decode_jwt
|
|
9
|
+
from .errors import (
|
|
10
|
+
APIError,
|
|
11
|
+
JWTExpiredError,
|
|
12
|
+
JWTInvalidPayloadFormat,
|
|
13
|
+
JWTInvalidTokenError,
|
|
14
|
+
)
|
|
15
|
+
from .models import Session
|
|
16
|
+
from .types import JWTPayload
|
|
17
|
+
|
|
18
|
+
User = get_user_model()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@dataclasses.dataclass
|
|
22
|
+
class AuthDetails:
|
|
23
|
+
user: User
|
|
24
|
+
session: Session
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclasses.dataclass
|
|
28
|
+
class AuthedRequest(HttpRequest):
|
|
29
|
+
auth: AuthDetails
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class JWTAuth(HttpBearer):
|
|
33
|
+
def authenticate(self, request: HttpRequest, token: str) -> AuthDetails | None:
|
|
34
|
+
try:
|
|
35
|
+
payload = decode_jwt(token, JWTPayload)
|
|
36
|
+
except JWTExpiredError:
|
|
37
|
+
raise APIError("expired_token", 401)
|
|
38
|
+
except (JWTInvalidPayloadFormat, JWTInvalidTokenError):
|
|
39
|
+
raise APIError("invalid_token", 401)
|
|
40
|
+
|
|
41
|
+
# Validate the Session
|
|
42
|
+
try:
|
|
43
|
+
session = Session.objects.get(id=payload.session_id)
|
|
44
|
+
except Session.DoesNotExist:
|
|
45
|
+
raise APIError("session_not_found", 401)
|
|
46
|
+
if session.expired_at and session.expired_at < timezone.now():
|
|
47
|
+
raise APIError("session_expired", 401)
|
|
48
|
+
|
|
49
|
+
# Validate the user
|
|
50
|
+
try:
|
|
51
|
+
user = User.objects.get(id=payload.user_id, is_active=True)
|
|
52
|
+
except User.DoesNotExist:
|
|
53
|
+
raise APIError("invalid_user", 401)
|
|
54
|
+
|
|
55
|
+
return AuthDetails(user=user, session=session)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
|
|
3
|
+
from django.contrib.auth import authenticate
|
|
4
|
+
from django.http import HttpRequest
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def django_user_authenticator(request: HttpRequest, payload: Any):
|
|
8
|
+
return authenticate(
|
|
9
|
+
request=request,
|
|
10
|
+
username=payload.username,
|
|
11
|
+
password=payload.password,
|
|
12
|
+
)
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
from typing import Type
|
|
2
|
+
|
|
3
|
+
import jwt
|
|
4
|
+
from pydantic import ValidationError
|
|
5
|
+
|
|
6
|
+
from .errors import JWTExpiredError, JWTInvalidPayloadFormat, JWTInvalidTokenError
|
|
7
|
+
from .settings import jwt_settings
|
|
8
|
+
from .types import JWTPayload
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def generate_jwt(payload: JWTPayload) -> str:
|
|
12
|
+
"""
|
|
13
|
+
Generates a JSON Web Token (JWT)
|
|
14
|
+
|
|
15
|
+
Args:
|
|
16
|
+
payload (JWTPayload): The data to include in the token payload.
|
|
17
|
+
|
|
18
|
+
Returns:
|
|
19
|
+
str: The encoded JWT as a string.
|
|
20
|
+
"""
|
|
21
|
+
return jwt.encode(
|
|
22
|
+
payload=payload.model_dump(mode="json"),
|
|
23
|
+
key=jwt_settings.SECRET_KEY,
|
|
24
|
+
algorithm=jwt_settings.ALGORITHM,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def decode_jwt(token: str, payload_class: Type[JWTPayload]) -> JWTPayload:
|
|
29
|
+
"""
|
|
30
|
+
Decodes a JSON Web Token (JWT) and returns the payload.
|
|
31
|
+
|
|
32
|
+
Args:
|
|
33
|
+
token (str): The encoded JWT as a string.
|
|
34
|
+
payload_class (Type[JWTPayload]): The class to deserialize the payload into.
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
JWTPayload: The deserialized payload.
|
|
38
|
+
|
|
39
|
+
Raises:
|
|
40
|
+
JWTExpiredError: If the token has expired.
|
|
41
|
+
JWTInvalidTokenError: If the token is invalid.
|
|
42
|
+
JWTInvalidPayloadFormat: If the payload format is invalid.
|
|
43
|
+
"""
|
|
44
|
+
try:
|
|
45
|
+
payload = jwt.decode(
|
|
46
|
+
jwt=token,
|
|
47
|
+
key=jwt_settings.SECRET_KEY,
|
|
48
|
+
algorithms=[jwt_settings.ALGORITHM],
|
|
49
|
+
)
|
|
50
|
+
|
|
51
|
+
except jwt.ExpiredSignatureError as err:
|
|
52
|
+
raise JWTExpiredError() from err
|
|
53
|
+
|
|
54
|
+
except jwt.InvalidTokenError as err:
|
|
55
|
+
raise JWTInvalidTokenError() from err
|
|
56
|
+
|
|
57
|
+
try:
|
|
58
|
+
return payload_class(**payload)
|
|
59
|
+
except ValidationError as exc:
|
|
60
|
+
raise JWTInvalidPayloadFormat() from exc
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
from typing import Literal
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class JWTError(Exception):
|
|
5
|
+
"""Base class for JWT exceptions."""
|
|
6
|
+
|
|
7
|
+
def __init__(
|
|
8
|
+
self,
|
|
9
|
+
error_code: str,
|
|
10
|
+
error_friendly: str,
|
|
11
|
+
http_status_code: int,
|
|
12
|
+
**kwargs,
|
|
13
|
+
):
|
|
14
|
+
self.error_code = error_code
|
|
15
|
+
self.error_friendly = error_friendly
|
|
16
|
+
self.http_status_code = http_status_code
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class JWTExpiredError(JWTError):
|
|
20
|
+
"""Exception raised when a JWT token has expired."""
|
|
21
|
+
|
|
22
|
+
def __init__(self, **kwargs):
|
|
23
|
+
super().__init__(
|
|
24
|
+
error_code="expired_token",
|
|
25
|
+
error_friendly="Token has expired",
|
|
26
|
+
http_status_code=401,
|
|
27
|
+
**kwargs,
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class JWTInvalidTokenError(JWTError):
|
|
32
|
+
"""Exception raised when a JWT token is invalid."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, **kwargs):
|
|
35
|
+
super().__init__(
|
|
36
|
+
error_code="invalid_token",
|
|
37
|
+
error_friendly="Token is invalid",
|
|
38
|
+
http_status_code=401,
|
|
39
|
+
**kwargs,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class JWTInvalidPayloadFormat(JWTError):
|
|
44
|
+
"""Exception raised when the JWT payload format is invalid."""
|
|
45
|
+
|
|
46
|
+
def __init__(self, **kwargs):
|
|
47
|
+
super().__init__(
|
|
48
|
+
error_code="invalid_payload_format",
|
|
49
|
+
error_friendly="Payload could not be deserialized",
|
|
50
|
+
http_status_code=401,
|
|
51
|
+
**kwargs,
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
ErrorCode = Literal[
|
|
56
|
+
"invalid_credentials",
|
|
57
|
+
"expired_token",
|
|
58
|
+
"invalid_token",
|
|
59
|
+
"invalid_token_type",
|
|
60
|
+
"invalid_user",
|
|
61
|
+
"invalid_token",
|
|
62
|
+
"session_not_found",
|
|
63
|
+
"session_expired",
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class APIError(Exception):
|
|
68
|
+
def __init__(self, error_code: ErrorCode, http_status_code: int):
|
|
69
|
+
self.error_code = error_code
|
|
70
|
+
self.http_status_code = http_status_code
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Generated by Django 5.1.2 on 2024-10-11 16:45
|
|
2
|
+
|
|
3
|
+
import django.core.serializers.json
|
|
4
|
+
import django.db.models.deletion
|
|
5
|
+
import functools
|
|
6
|
+
import secrets
|
|
7
|
+
from django.conf import settings
|
|
8
|
+
from django.db import migrations, models
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class Migration(migrations.Migration):
|
|
12
|
+
|
|
13
|
+
initial = True
|
|
14
|
+
|
|
15
|
+
dependencies = [
|
|
16
|
+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
operations = [
|
|
20
|
+
migrations.CreateModel(
|
|
21
|
+
name='Session',
|
|
22
|
+
fields=[
|
|
23
|
+
('id', models.CharField(default=functools.partial(secrets.token_urlsafe, *(32,), **{}), max_length=43, primary_key=True, serialize=False)),
|
|
24
|
+
('created_at', models.DateTimeField(auto_now_add=True)),
|
|
25
|
+
('updated_at', models.DateTimeField(auto_now=True)),
|
|
26
|
+
('expired_at', models.DateTimeField(blank=True, db_index=True, null=True)),
|
|
27
|
+
('ip_address', models.GenericIPAddressField(blank=True, null=True)),
|
|
28
|
+
('data', models.JSONField(default=dict, encoder=django.core.serializers.json.DjangoJSONEncoder)),
|
|
29
|
+
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='jwt_sessions', to=settings.AUTH_USER_MODEL)),
|
|
30
|
+
],
|
|
31
|
+
options={
|
|
32
|
+
'verbose_name': 'JWT Session',
|
|
33
|
+
'verbose_name_plural': 'JWT Sessions',
|
|
34
|
+
'indexes': [models.Index(condition=models.Q(('expired_at__isnull', False)), fields=['expired_at'], name='idx_non_null_expired_at'), models.Index(fields=['user'], name='jwt_ninja_s_user_id_5c569c_idx')],
|
|
35
|
+
},
|
|
36
|
+
),
|
|
37
|
+
]
|
|
File without changes
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
from functools import cached_property, partial
|
|
2
|
+
from secrets import token_urlsafe
|
|
3
|
+
|
|
4
|
+
from django.contrib.auth import get_user_model
|
|
5
|
+
from django.core.serializers.json import DjangoJSONEncoder
|
|
6
|
+
from django.db import models
|
|
7
|
+
from django.utils import timezone
|
|
8
|
+
|
|
9
|
+
User = get_user_model()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Session(models.Model):
|
|
13
|
+
class Meta:
|
|
14
|
+
verbose_name = "JWT Session"
|
|
15
|
+
verbose_name_plural = "JWT Sessions"
|
|
16
|
+
|
|
17
|
+
indexes = [
|
|
18
|
+
models.Index(
|
|
19
|
+
fields=["expired_at"],
|
|
20
|
+
name="idx_non_null_expired_at",
|
|
21
|
+
condition=models.Q(expired_at__isnull=False),
|
|
22
|
+
),
|
|
23
|
+
models.Index(fields=["user"]),
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
id = models.CharField(
|
|
27
|
+
primary_key=True,
|
|
28
|
+
max_length=43, # token_urlsafe(32) is 43 chars
|
|
29
|
+
default=partial(token_urlsafe, 32),
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
# Dates
|
|
33
|
+
created_at = models.DateTimeField(auto_now_add=True)
|
|
34
|
+
updated_at = models.DateTimeField(auto_now=True)
|
|
35
|
+
expired_at = models.DateTimeField(
|
|
36
|
+
null=True,
|
|
37
|
+
blank=True,
|
|
38
|
+
db_index=True,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
ip_address = models.GenericIPAddressField(
|
|
42
|
+
blank=True,
|
|
43
|
+
null=True,
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
user = models.ForeignKey(
|
|
47
|
+
User,
|
|
48
|
+
on_delete=models.CASCADE,
|
|
49
|
+
related_name="jwt_sessions",
|
|
50
|
+
)
|
|
51
|
+
|
|
52
|
+
data = models.JSONField(
|
|
53
|
+
default=dict,
|
|
54
|
+
encoder=DjangoJSONEncoder,
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
@cached_property
|
|
58
|
+
def is_expired(self):
|
|
59
|
+
return self.expired_at and self.expired_at < timezone.now()
|
|
60
|
+
|
|
61
|
+
def invalidate_session(self):
|
|
62
|
+
"""
|
|
63
|
+
Explicitly invalidate a session.
|
|
64
|
+
"""
|
|
65
|
+
self.expired_at = timezone.now()
|
|
66
|
+
self.save()
|
|
67
|
+
|
|
68
|
+
@classmethod
|
|
69
|
+
def invalidate_all_user_sessions(cls, user):
|
|
70
|
+
"""
|
|
71
|
+
Invalidate all sessions for a user.
|
|
72
|
+
"""
|
|
73
|
+
now = timezone.now()
|
|
74
|
+
return cls.objects.filter(
|
|
75
|
+
user=user,
|
|
76
|
+
expired_at__isnull=True,
|
|
77
|
+
).update(
|
|
78
|
+
expired_at=now,
|
|
79
|
+
updated_at=now,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
@classmethod
|
|
83
|
+
def purge_expired_sessions(cls):
|
|
84
|
+
"""
|
|
85
|
+
Delete sessions that have expired.
|
|
86
|
+
"""
|
|
87
|
+
return cls.objects.filter(
|
|
88
|
+
expired_at__lt=timezone.now(),
|
|
89
|
+
).delete()
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def create_session(cls, user, ip_address: str) -> "Session":
|
|
93
|
+
"""
|
|
94
|
+
Create a new session from a request.
|
|
95
|
+
"""
|
|
96
|
+
current_utc = timezone.now()
|
|
97
|
+
return cls.objects.create(
|
|
98
|
+
user=user,
|
|
99
|
+
created_at=current_utc,
|
|
100
|
+
updated_at=current_utc,
|
|
101
|
+
ip_address=ip_address,
|
|
102
|
+
)
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from django.http import HttpRequest
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def get_client_ip(request: HttpRequest) -> str:
|
|
5
|
+
"""
|
|
6
|
+
Retrieve the client IP address from the given HttpRequest.
|
|
7
|
+
|
|
8
|
+
Args:
|
|
9
|
+
request (HttpRequest): The HTTP request object.
|
|
10
|
+
|
|
11
|
+
Returns:
|
|
12
|
+
str: The client IP address.
|
|
13
|
+
"""
|
|
14
|
+
x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR")
|
|
15
|
+
if x_forwarded_for:
|
|
16
|
+
return x_forwarded_for.split(",")[0]
|
|
17
|
+
else:
|
|
18
|
+
return request.META.get("REMOTE_ADDR")
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
from django.conf import settings
|
|
2
|
+
from django.core.signals import setting_changed
|
|
3
|
+
from django.utils.module_loading import import_string
|
|
4
|
+
from pydantic import Field
|
|
5
|
+
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class JWTSettings(BaseSettings):
|
|
9
|
+
SECRET_KEY: str = Field(settings.SECRET_KEY)
|
|
10
|
+
ALGORITHM: str = "HS256"
|
|
11
|
+
ACCESS_TOKEN_EXPIRE_SECONDS: int = 300 # 5 minutes
|
|
12
|
+
REFRESH_TOKEN_EXPIRE_SECONDS: int = 365 * 3600 # 1 year
|
|
13
|
+
SESSION_EXPIRE_SECONDS: int = 365 * 3600 # 1 year
|
|
14
|
+
USER_LOGIN_AUTHENTICATOR: str = "jwt_ninja.authenticators.django_user_authenticator"
|
|
15
|
+
JWT_PAYLOAD_CLASS: str = "jwt_ninja.types.JWTPayload"
|
|
16
|
+
|
|
17
|
+
model_config = SettingsConfigDict(
|
|
18
|
+
env_prefix="JWT_",
|
|
19
|
+
case_sensitive=True,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
def __init__(self):
|
|
23
|
+
super().__init__()
|
|
24
|
+
self._USER_LOGIN_AUTHENTICATOR = import_string(self.USER_LOGIN_AUTHENTICATOR)
|
|
25
|
+
self._JWT_PAYLOAD_CLASS = import_string(self.JWT_PAYLOAD_CLASS)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
jwt_settings = JWTSettings()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def reload_jwt_settings(*args, **kwargs):
|
|
32
|
+
setting = kwargs["setting"]
|
|
33
|
+
if setting.startswith("JWT_"):
|
|
34
|
+
global jwt_settings
|
|
35
|
+
jwt_settings = JWTSettings()
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
setting_changed.connect(reload_jwt_settings)
|
|
File without changes
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import time
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
from django.contrib.auth import get_user_model
|
|
5
|
+
from django.utils import timezone
|
|
6
|
+
from ninja import NinjaAPI
|
|
7
|
+
from ninja.testing import TestClient
|
|
8
|
+
|
|
9
|
+
from ..api import router
|
|
10
|
+
from ..auth_classes import AuthedRequest, JWTAuth
|
|
11
|
+
from ..cryptography import generate_jwt
|
|
12
|
+
from ..errors import APIError
|
|
13
|
+
from ..handlers import error_handler
|
|
14
|
+
from ..models import Session
|
|
15
|
+
from ..types import JWTPayload
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
User = get_user_model()
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def jwt_auth():
|
|
23
|
+
return JWTAuth()
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.fixture(scope="session")
|
|
27
|
+
def ninja_client() -> TestClient:
|
|
28
|
+
def sample_view(request: AuthedRequest):
|
|
29
|
+
return {"message": "secret_th1ngs"}
|
|
30
|
+
|
|
31
|
+
api = NinjaAPI()
|
|
32
|
+
api.add_router("auth/", router)
|
|
33
|
+
api.api_operation(["GET"], "auth/protected/", auth=JWTAuth())(sample_view)
|
|
34
|
+
api.exception_handler(APIError)(error_handler)
|
|
35
|
+
|
|
36
|
+
return TestClient(api)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
@pytest.fixture
|
|
40
|
+
def test_user() -> User:
|
|
41
|
+
return User.objects.create_user(
|
|
42
|
+
email="dan@example.com",
|
|
43
|
+
username="dan",
|
|
44
|
+
password="dan",
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@pytest.fixture
|
|
49
|
+
def one_hour_from_now() -> int:
|
|
50
|
+
return int(time.time()) + 3600
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@pytest.fixture
|
|
54
|
+
def seven_days_from_now() -> int:
|
|
55
|
+
return int(time.time()) + 7 * 24 * 3600
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@pytest.fixture
|
|
59
|
+
def user_session(test_user) -> Session:
|
|
60
|
+
"""
|
|
61
|
+
Fixture to generate a valid session token for the test user.
|
|
62
|
+
"""
|
|
63
|
+
return Session.create_session(user=test_user, ip_address="192.168.1.99")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
@pytest.fixture
|
|
67
|
+
def access_token(test_user, user_session, one_hour_from_now) -> str:
|
|
68
|
+
"""
|
|
69
|
+
Fixture to generate a valid access token for the test user.
|
|
70
|
+
"""
|
|
71
|
+
payload = JWTPayload(
|
|
72
|
+
user_id=test_user.id,
|
|
73
|
+
type="access",
|
|
74
|
+
exp=one_hour_from_now,
|
|
75
|
+
session_id=user_session.id,
|
|
76
|
+
)
|
|
77
|
+
return generate_jwt(payload)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
@pytest.fixture
|
|
81
|
+
def expired_sessions(test_user, user_session, freezer) -> list[Session]:
|
|
82
|
+
"""
|
|
83
|
+
Fixture to generate expired sessions for the user.
|
|
84
|
+
"""
|
|
85
|
+
freezer.move_to("2022-01-01 12:00:00")
|
|
86
|
+
timestamp = timezone.now()
|
|
87
|
+
|
|
88
|
+
return [
|
|
89
|
+
Session.objects.create(
|
|
90
|
+
user=test_user,
|
|
91
|
+
created_at=timestamp,
|
|
92
|
+
updated_at=timestamp,
|
|
93
|
+
expired_at=timestamp,
|
|
94
|
+
ip_address="192.168.1.1",
|
|
95
|
+
),
|
|
96
|
+
Session.objects.create(
|
|
97
|
+
user=test_user,
|
|
98
|
+
created_at=timestamp,
|
|
99
|
+
updated_at=timestamp,
|
|
100
|
+
expired_at=timestamp,
|
|
101
|
+
ip_address="192.168.1.2",
|
|
102
|
+
),
|
|
103
|
+
]
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
@pytest.fixture
|
|
107
|
+
def refresh_token(test_user, user_session, seven_days_from_now) -> str:
|
|
108
|
+
"""
|
|
109
|
+
Fixture to generate a valid refresh token for the test user.
|
|
110
|
+
"""
|
|
111
|
+
payload = JWTPayload(
|
|
112
|
+
user_id=test_user.id,
|
|
113
|
+
type="refresh",
|
|
114
|
+
exp=seven_days_from_now,
|
|
115
|
+
session_id=user_session.id,
|
|
116
|
+
)
|
|
117
|
+
return generate_jwt(payload)
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import json
|
|
3
|
+
import time
|
|
4
|
+
from datetime import timedelta
|
|
5
|
+
|
|
6
|
+
import pytest
|
|
7
|
+
from django.utils import timezone
|
|
8
|
+
|
|
9
|
+
from ..cryptography import generate_jwt
|
|
10
|
+
from ..models import Session
|
|
11
|
+
from ..types import JWTPayload
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@pytest.mark.django_db
|
|
15
|
+
def test_login_success_happy(ninja_client, test_user):
|
|
16
|
+
res = ninja_client.post(
|
|
17
|
+
"/auth/login/",
|
|
18
|
+
json={
|
|
19
|
+
"username": "dan",
|
|
20
|
+
"password": "dan",
|
|
21
|
+
},
|
|
22
|
+
)
|
|
23
|
+
|
|
24
|
+
assert res.status_code == 200
|
|
25
|
+
json_response = res.json()
|
|
26
|
+
|
|
27
|
+
assert "access_token" in json_response
|
|
28
|
+
assert "refresh_token" in json_response
|
|
29
|
+
|
|
30
|
+
# Check the contents of the JWT payload
|
|
31
|
+
dec_access_token = json.loads(
|
|
32
|
+
base64.b64decode(json_response["access_token"].split(".")[1] + "===").decode()
|
|
33
|
+
)
|
|
34
|
+
assert dec_access_token["user_id"] == test_user.id
|
|
35
|
+
assert dec_access_token["type"] == "access"
|
|
36
|
+
assert dec_access_token["session_id"]
|
|
37
|
+
assert dec_access_token["exp"]
|
|
38
|
+
|
|
39
|
+
dec_refresh_token = json.loads(
|
|
40
|
+
base64.b64decode(json_response["refresh_token"].split(".")[1] + "===").decode()
|
|
41
|
+
)
|
|
42
|
+
assert dec_refresh_token["user_id"] == test_user.id
|
|
43
|
+
assert dec_refresh_token["type"] == "refresh"
|
|
44
|
+
assert dec_refresh_token["session_id"] == dec_access_token["session_id"]
|
|
45
|
+
assert dec_refresh_token["exp"]
|
|
46
|
+
|
|
47
|
+
assert test_user.jwt_sessions.count() == 1
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@pytest.mark.django_db
|
|
51
|
+
def test_login_failure(ninja_client):
|
|
52
|
+
res = ninja_client.post(
|
|
53
|
+
"/auth/login/",
|
|
54
|
+
json={
|
|
55
|
+
"username": "wronguser",
|
|
56
|
+
"password": "wrongpass",
|
|
57
|
+
},
|
|
58
|
+
)
|
|
59
|
+
|
|
60
|
+
assert res.status_code == 401
|
|
61
|
+
json_response = res.json()
|
|
62
|
+
assert json_response["error_code"] == "invalid_credentials"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@pytest.mark.django_db
|
|
66
|
+
def test_refresh_token_success(ninja_client, refresh_token, test_user):
|
|
67
|
+
res = ninja_client.post(
|
|
68
|
+
"/auth/refresh/",
|
|
69
|
+
json={
|
|
70
|
+
"refresh_token": refresh_token,
|
|
71
|
+
},
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
assert res.status_code == 200
|
|
75
|
+
json_response = res.json()
|
|
76
|
+
assert "access_token" in json_response
|
|
77
|
+
|
|
78
|
+
dec_access_token = json.loads(
|
|
79
|
+
base64.b64decode(json_response["access_token"].split(".")[1] + "===").decode()
|
|
80
|
+
)
|
|
81
|
+
assert dec_access_token["user_id"] == test_user.id
|
|
82
|
+
assert dec_access_token["type"] == "access"
|
|
83
|
+
assert dec_access_token["exp"]
|
|
84
|
+
assert dec_access_token["session_id"]
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@pytest.mark.django_db
|
|
88
|
+
def test_refresh_token_failure_invalid_token(ninja_client):
|
|
89
|
+
response = ninja_client.post(
|
|
90
|
+
"/auth/refresh/",
|
|
91
|
+
json={
|
|
92
|
+
"refresh_token": "invalidtoken",
|
|
93
|
+
},
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
assert response.status_code == 401
|
|
97
|
+
json_response = response.json()
|
|
98
|
+
assert "error_code" in json_response
|
|
99
|
+
assert json_response["error_code"] == "invalid_token"
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@pytest.mark.django_db
|
|
103
|
+
def test_protected_endpoint_success(ninja_client, access_token):
|
|
104
|
+
response = ninja_client.get(
|
|
105
|
+
"/auth/protected/",
|
|
106
|
+
headers={
|
|
107
|
+
"Authorization": f"Bearer {access_token}",
|
|
108
|
+
},
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
assert response.status_code == 200
|
|
112
|
+
json_response = response.json()
|
|
113
|
+
assert "message" in json_response
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
@pytest.mark.django_db
|
|
117
|
+
def test_protected_endpoint_expired_session(ninja_client, access_token, user_session):
|
|
118
|
+
user_session.expired_at = timezone.now()
|
|
119
|
+
user_session.save()
|
|
120
|
+
|
|
121
|
+
response = ninja_client.get(
|
|
122
|
+
"/auth/protected/",
|
|
123
|
+
headers={
|
|
124
|
+
"Authorization": f"Bearer {access_token}",
|
|
125
|
+
},
|
|
126
|
+
)
|
|
127
|
+
|
|
128
|
+
assert response.status_code == 401
|
|
129
|
+
json_response = response.json()
|
|
130
|
+
assert json_response["error_code"] == "session_expired"
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
@pytest.mark.django_db
|
|
134
|
+
def test_protected_endpoint_fails_with_wrong_token(ninja_client, access_token):
|
|
135
|
+
response = ninja_client.get(
|
|
136
|
+
"/auth/protected/",
|
|
137
|
+
headers={
|
|
138
|
+
"Authorization": f"Bearer {access_token}+1",
|
|
139
|
+
},
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
assert response.status_code == 401
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
@pytest.mark.django_db
|
|
146
|
+
def test_protected_endpoint_failure_no_token(ninja_client):
|
|
147
|
+
response = ninja_client.get("/auth/protected/")
|
|
148
|
+
|
|
149
|
+
assert response.status_code == 401
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
@pytest.mark.django_db
|
|
153
|
+
def test_access_token_expired(ninja_client, test_user, user_session, freezer):
|
|
154
|
+
payload = JWTPayload(
|
|
155
|
+
user_id=test_user.id,
|
|
156
|
+
type="access",
|
|
157
|
+
exp=int(time.time()) + 1,
|
|
158
|
+
session_id=user_session.id,
|
|
159
|
+
)
|
|
160
|
+
token = generate_jwt(payload)
|
|
161
|
+
|
|
162
|
+
# Move 10 secs in the future
|
|
163
|
+
freezer.tick(delta=timedelta(seconds=10))
|
|
164
|
+
|
|
165
|
+
response = ninja_client.get(
|
|
166
|
+
"/auth/protected/",
|
|
167
|
+
headers={
|
|
168
|
+
"Authorization": f"Bearer {token}",
|
|
169
|
+
},
|
|
170
|
+
)
|
|
171
|
+
|
|
172
|
+
assert response.status_code == 401
|
|
173
|
+
json_response = response.json()
|
|
174
|
+
assert "error_code" in json_response
|
|
175
|
+
assert json_response["error_code"] == "expired_token"
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
@pytest.mark.django_db
|
|
179
|
+
def test_refresh_token_expired(ninja_client, user_session, test_user, freezer):
|
|
180
|
+
payload = JWTPayload(
|
|
181
|
+
user_id=test_user.id,
|
|
182
|
+
type="refresh",
|
|
183
|
+
exp=int(time.time()) + 1,
|
|
184
|
+
session_id=user_session.id,
|
|
185
|
+
)
|
|
186
|
+
token = generate_jwt(payload)
|
|
187
|
+
|
|
188
|
+
freezer.tick(delta=timedelta(seconds=10))
|
|
189
|
+
|
|
190
|
+
response = ninja_client.post(
|
|
191
|
+
"/auth/refresh/",
|
|
192
|
+
json={
|
|
193
|
+
"refresh_token": token,
|
|
194
|
+
},
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
assert response.status_code == 401
|
|
198
|
+
json_response = response.json()
|
|
199
|
+
assert "error_code" in json_response
|
|
200
|
+
assert json_response["error_code"] == "expired_token"
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
@pytest.mark.django_db
|
|
204
|
+
def test_logout(ninja_client, access_token, test_user, user_session):
|
|
205
|
+
response = ninja_client.post(
|
|
206
|
+
"/auth/logout/",
|
|
207
|
+
headers={
|
|
208
|
+
"Authorization": f"Bearer {access_token}",
|
|
209
|
+
},
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
user_session.refresh_from_db()
|
|
213
|
+
|
|
214
|
+
assert response.status_code == 200
|
|
215
|
+
assert user_session.expired_at is not None
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@pytest.mark.django_db
|
|
219
|
+
def test_logout_all(ninja_client, access_token, test_user, user_session):
|
|
220
|
+
# Create another active session
|
|
221
|
+
other_session = Session.create_session(user=test_user, ip_address="129.168.7.7")
|
|
222
|
+
|
|
223
|
+
response = ninja_client.post(
|
|
224
|
+
"/auth/logout/all/",
|
|
225
|
+
headers={
|
|
226
|
+
"Authorization": f"Bearer {access_token}",
|
|
227
|
+
},
|
|
228
|
+
)
|
|
229
|
+
assert response.status_code == 200
|
|
230
|
+
|
|
231
|
+
user_session.refresh_from_db()
|
|
232
|
+
other_session.refresh_from_db()
|
|
233
|
+
|
|
234
|
+
assert user_session.expired_at is not None
|
|
235
|
+
assert other_session.expired_at is not None
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import pytest
|
|
2
|
+
from django.contrib.auth import get_user_model
|
|
3
|
+
from django.http import HttpRequest
|
|
4
|
+
from django.utils import timezone
|
|
5
|
+
|
|
6
|
+
from ..errors import APIError, JWTExpiredError, JWTInvalidTokenError
|
|
7
|
+
from ..models import Session
|
|
8
|
+
|
|
9
|
+
User = get_user_model()
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def create_request(headers: dict[str, str] = None):
|
|
13
|
+
"""
|
|
14
|
+
Helper function to create a normal Django HttpRequest
|
|
15
|
+
"""
|
|
16
|
+
request = HttpRequest()
|
|
17
|
+
request.META = headers or {}
|
|
18
|
+
return request
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.fixture
|
|
22
|
+
def user(mocker):
|
|
23
|
+
return mocker.MagicMock(id=111)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.fixture
|
|
27
|
+
def session(mocker):
|
|
28
|
+
return mocker.MagicMock(id=333, expired_at=None)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@pytest.fixture
|
|
32
|
+
def payload(mocker, user, session):
|
|
33
|
+
return mocker.MagicMock(user_id=user.id, session_id=session.id)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@pytest.fixture
|
|
37
|
+
def req():
|
|
38
|
+
return create_request()
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_authenticate_valid_token(req, jwt_auth, user, payload, session, mocker):
|
|
42
|
+
token = "valid_token"
|
|
43
|
+
|
|
44
|
+
mocker.patch("jwt_ninja.auth_classes.decode_jwt", return_value=payload)
|
|
45
|
+
mocker.patch("jwt_ninja.auth_classes.User.objects.get", return_value=user)
|
|
46
|
+
mocker.patch("jwt_ninja.auth_classes.Session.objects.get", return_value=session)
|
|
47
|
+
|
|
48
|
+
auth_details = jwt_auth.authenticate(req, token)
|
|
49
|
+
|
|
50
|
+
assert auth_details.user == user
|
|
51
|
+
assert auth_details.session == session
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_authenticate_invalid_token(jwt_auth, req, mocker):
|
|
55
|
+
token = "invalid_token"
|
|
56
|
+
|
|
57
|
+
mocker.patch("jwt_ninja.auth_classes.decode_jwt", side_effect=JWTInvalidTokenError)
|
|
58
|
+
with pytest.raises(APIError) as exc_info:
|
|
59
|
+
jwt_auth.authenticate(req, token)
|
|
60
|
+
|
|
61
|
+
assert exc_info.value.error_code == "invalid_token"
|
|
62
|
+
assert exc_info.value.http_status_code == 401
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def test_authenticate_expired_token(jwt_auth, req, mocker):
|
|
66
|
+
token = "expired_token"
|
|
67
|
+
|
|
68
|
+
mocker.patch("jwt_ninja.auth_classes.decode_jwt", side_effect=JWTExpiredError)
|
|
69
|
+
with pytest.raises(APIError) as exc_info:
|
|
70
|
+
jwt_auth.authenticate(req, token)
|
|
71
|
+
|
|
72
|
+
assert exc_info.value.error_code == "expired_token"
|
|
73
|
+
assert exc_info.value.http_status_code == 401
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def test_authenticate_expired_session(
|
|
77
|
+
jwt_auth,
|
|
78
|
+
payload,
|
|
79
|
+
user,
|
|
80
|
+
session,
|
|
81
|
+
req,
|
|
82
|
+
mocker,
|
|
83
|
+
freezer,
|
|
84
|
+
):
|
|
85
|
+
token = "valid_token"
|
|
86
|
+
|
|
87
|
+
session.expired_at = timezone.now()
|
|
88
|
+
|
|
89
|
+
freezer.tick() # move forward by 1 sec into the future
|
|
90
|
+
|
|
91
|
+
mocker.patch("jwt_ninja.auth_classes.decode_jwt", return_value=payload)
|
|
92
|
+
mocker.patch("jwt_ninja.auth_classes.User.objects.get", return_value=user)
|
|
93
|
+
mocker.patch("jwt_ninja.auth_classes.Session.objects.get", return_value=session)
|
|
94
|
+
with pytest.raises(APIError) as exc_info:
|
|
95
|
+
jwt_auth.authenticate(req, token)
|
|
96
|
+
|
|
97
|
+
assert exc_info.value.error_code == "session_expired"
|
|
98
|
+
assert exc_info.value.http_status_code == 401
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def test_authenticate_session_not_found(jwt_auth, payload, user, req, mocker):
|
|
102
|
+
token = "valid_token"
|
|
103
|
+
|
|
104
|
+
# this is the exception we want to simulate
|
|
105
|
+
initial_exc = Session.DoesNotExist
|
|
106
|
+
|
|
107
|
+
mocker.patch("jwt_ninja.auth_classes.decode_jwt", return_value=payload)
|
|
108
|
+
mocker.patch("jwt_ninja.auth_classes.User.objects.get", return_value=user)
|
|
109
|
+
mocker.patch("jwt_ninja.auth_classes.Session.objects.get", side_effect=initial_exc)
|
|
110
|
+
with pytest.raises(APIError) as exc_info:
|
|
111
|
+
jwt_auth.authenticate(req, token)
|
|
112
|
+
|
|
113
|
+
assert exc_info.value.error_code == "session_not_found"
|
|
114
|
+
assert exc_info.value.http_status_code == 401
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_authenticate_user_not_found(jwt_auth, mocker, payload, session, req):
|
|
118
|
+
token = "valid_token"
|
|
119
|
+
|
|
120
|
+
initial_exc = User.DoesNotExist
|
|
121
|
+
|
|
122
|
+
mocker.patch("jwt_ninja.auth_classes.decode_jwt", return_value=payload)
|
|
123
|
+
mocker.patch("jwt_ninja.auth_classes.User.objects.get", side_effect=initial_exc)
|
|
124
|
+
mocker.patch("jwt_ninja.auth_classes.Session.objects.get", return_value=session)
|
|
125
|
+
with pytest.raises(APIError) as exc_info:
|
|
126
|
+
jwt_auth.authenticate(req, token)
|
|
127
|
+
|
|
128
|
+
assert exc_info.value.error_code == "invalid_user"
|
|
129
|
+
assert exc_info.value.http_status_code == 401
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
from datetime import datetime
|
|
2
|
+
from typing import Generic, Literal, TypeVar
|
|
3
|
+
from uuid import UUID
|
|
4
|
+
|
|
5
|
+
from pydantic import BaseModel, Field
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class JWTPayload(BaseModel):
|
|
9
|
+
type: Literal["access", "refresh"]
|
|
10
|
+
exp: int
|
|
11
|
+
|
|
12
|
+
# Custom claims
|
|
13
|
+
user_id: int
|
|
14
|
+
session_id: str
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class LoginSchema(BaseModel):
|
|
18
|
+
username: str
|
|
19
|
+
password: str
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class TokenSchema(BaseModel):
|
|
23
|
+
access_token: str
|
|
24
|
+
refresh_token: str
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class RefreshTokenSchema(BaseModel):
|
|
28
|
+
refresh_token: str
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AccessTokenSchema(BaseModel):
|
|
32
|
+
access_token: str
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
E = TypeVar("E", bound=str)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class ErrorResponseType(BaseModel, Generic[E]):
|
|
39
|
+
error_code: E
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class SessionResponse(BaseModel):
|
|
43
|
+
id: UUID
|
|
44
|
+
created_at: datetime
|
|
45
|
+
last_activity_at: datetime = Field(alias="updated_at")
|
|
46
|
+
ip_address: str
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: jwtninja
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Add your description here
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: pydantic>=2.9.2
|
|
8
|
+
Requires-Dist: pydantic-settings>=2.5.2
|
|
9
|
+
Requires-Dist: uuid6>=2024.7.10
|
|
10
|
+
Requires-Dist: pyjwt>=2.9.0
|
|
11
|
+
Requires-Dist: django-ninja>=1.3.0
|
|
12
|
+
|
|
13
|
+
# JWT Ninja
|
|
14
|
+
|
|
15
|
+
A simple and fully-typed auth library for Django Ninja based on PyJWT.
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
pyproject.toml
|
|
3
|
+
jwt_ninja/__init__.py
|
|
4
|
+
jwt_ninja/admin.py
|
|
5
|
+
jwt_ninja/api.py
|
|
6
|
+
jwt_ninja/auth_classes.py
|
|
7
|
+
jwt_ninja/authenticators.py
|
|
8
|
+
jwt_ninja/cryptography.py
|
|
9
|
+
jwt_ninja/errors.py
|
|
10
|
+
jwt_ninja/handlers.py
|
|
11
|
+
jwt_ninja/models.py
|
|
12
|
+
jwt_ninja/request.py
|
|
13
|
+
jwt_ninja/settings.py
|
|
14
|
+
jwt_ninja/types.py
|
|
15
|
+
jwt_ninja/migrations/0001_initial.py
|
|
16
|
+
jwt_ninja/migrations/__init__.py
|
|
17
|
+
jwt_ninja/tests/__init__.py
|
|
18
|
+
jwt_ninja/tests/conftest.py
|
|
19
|
+
jwt_ninja/tests/django_settings.py
|
|
20
|
+
jwt_ninja/tests/test_api_endpoints.py
|
|
21
|
+
jwt_ninja/tests/test_jwt_auth.py
|
|
22
|
+
jwtninja.egg-info/PKG-INFO
|
|
23
|
+
jwtninja.egg-info/SOURCES.txt
|
|
24
|
+
jwtninja.egg-info/dependency_links.txt
|
|
25
|
+
jwtninja.egg-info/requires.txt
|
|
26
|
+
jwtninja.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
jwt_ninja
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "jwtninja"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
description = "Add your description here"
|
|
5
|
+
readme = "README.md"
|
|
6
|
+
requires-python = ">=3.12"
|
|
7
|
+
dependencies = [
|
|
8
|
+
"pydantic>=2.9.2",
|
|
9
|
+
"pydantic-settings>=2.5.2",
|
|
10
|
+
"uuid6>=2024.7.10",
|
|
11
|
+
"pyjwt>=2.9.0",
|
|
12
|
+
"django-ninja>=1.3.0",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[tool.uv]
|
|
16
|
+
dev-dependencies = [
|
|
17
|
+
"pytest-django>=4.9.0",
|
|
18
|
+
"pytest-freezer>=0.4.8",
|
|
19
|
+
"pytest-mock>=3.14.0",
|
|
20
|
+
"pytest>=8.3.3",
|
|
21
|
+
"ruff>=0.6.9",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[tool.ruff]
|
|
25
|
+
exclude = [
|
|
26
|
+
".git",
|
|
27
|
+
".github",
|
|
28
|
+
".venv",
|
|
29
|
+
".vscode",
|
|
30
|
+
"migrations",
|
|
31
|
+
"static_files",
|
|
32
|
+
]
|
jwtninja-0.1.0/setup.cfg
ADDED