djangorestframework-jwt-treet 1.12.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.
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2014-2017 Blimp LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.1
2
+ Name: djangorestframework-jwt-treet
3
+ Version: 1.12.0
4
+ Summary: JSON Web Token Authentication support for Django REST Framework
5
+ Author: José Padilla
6
+ Requires-Python: >=3.8,<4.0
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: Programming Language :: Python :: 3.8
9
+ Classifier: Programming Language :: Python :: 3.9
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Requires-Dist: pyjwt (>=1.5.2,<2.0.0)
@@ -0,0 +1,22 @@
1
+ [tool.poetry]
2
+ name = "djangorestframework-jwt-treet"
3
+ version = "1.12.0"
4
+ description = "JSON Web Token Authentication support for Django REST Framework"
5
+ authors = ["José Padilla"]
6
+ packages = [{ include = "rest_framework_jwt" }]
7
+
8
+ [tool.poetry.dependencies]
9
+ python = "^3.8"
10
+ pyjwt = ">=1.5.2,<2.0.0"
11
+
12
+ [tool.poetry.dev-dependencies]
13
+ black = "^22.3.0"
14
+ flake8 = "^4.0.1"
15
+
16
+ [tool.poetry.group.dev.dependencies]
17
+ pytest = "^7.4.2"
18
+ pytest-django = "^4.5.2"
19
+ cryptography = "^41.0.4"
20
+ django = "^4.2.0"
21
+ djangorestframework = "3.14.0"
22
+ pytest-cov = "^4.1.0"
@@ -0,0 +1,10 @@
1
+ # -*- coding: utf-8 -*-
2
+
3
+ __title__ = "djangorestframework-jwt"
4
+ __version__ = "1.11.0"
5
+ __author__ = "José Padilla"
6
+ __license__ = "MIT"
7
+ __copyright__ = "Copyright 2014-2017 Blimp LLC"
8
+
9
+ # Version synonym
10
+ VERSION = __version__
@@ -0,0 +1,115 @@
1
+ import jwt
2
+
3
+ from django.contrib.auth import get_user_model
4
+ from django.contrib.auth.models import User
5
+ from django.utils.encoding import smart_str
6
+ from django.utils.translation import gettext as _
7
+ from rest_framework import exceptions
8
+ from rest_framework.authentication import BaseAuthentication, get_authorization_header
9
+ from rest_framework.request import Request
10
+ from typing import Any, Dict, Tuple
11
+
12
+ from rest_framework_jwt.settings import api_settings
13
+
14
+
15
+ jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
16
+ jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER
17
+
18
+
19
+ class BaseJSONWebTokenAuthentication(BaseAuthentication):
20
+ """
21
+ Token based authentication using the JSON Web Token standard.
22
+ """
23
+
24
+ def authenticate(self, request: Request) -> Tuple[User, Dict[str, Any]]:
25
+ """
26
+ Returns a two-tuple of `User` and token if a valid signature has been
27
+ supplied using JWT-based authentication. Otherwise returns `None`.
28
+ """
29
+ jwt_value = self.get_jwt_value(request)
30
+ if jwt_value is None:
31
+ return None
32
+
33
+ try:
34
+ payload = jwt_decode_handler(jwt_value)
35
+ except jwt.ExpiredSignature:
36
+ msg = _("Signature has expired.")
37
+ raise exceptions.AuthenticationFailed(msg)
38
+ except jwt.DecodeError:
39
+ msg = _("Error decoding signature.")
40
+ raise exceptions.AuthenticationFailed(msg)
41
+ except jwt.InvalidTokenError:
42
+ raise exceptions.AuthenticationFailed()
43
+
44
+ user = self.authenticate_credentials(payload)
45
+
46
+ return (user, payload)
47
+
48
+ def authenticate_credentials(self, payload: Dict[str, Any]) -> User:
49
+ """
50
+ Returns an active user that matches the payload's user id and email.
51
+ """
52
+ User = get_user_model()
53
+ username = jwt_get_username_from_payload(payload)
54
+
55
+ if not username:
56
+ msg = _("Invalid payload.")
57
+ raise exceptions.AuthenticationFailed(msg)
58
+
59
+ try:
60
+ user = User.objects.get_by_natural_key(username)
61
+ except User.DoesNotExist:
62
+ msg = _("Invalid signature.")
63
+ raise exceptions.AuthenticationFailed(msg)
64
+
65
+ if not user.is_active:
66
+ msg = _("User account is disabled.")
67
+ raise exceptions.AuthenticationFailed(msg)
68
+
69
+ return user
70
+
71
+
72
+ class JSONWebTokenAuthentication(BaseJSONWebTokenAuthentication):
73
+ """
74
+ Clients should authenticate by passing the token key in the "Authorization"
75
+ HTTP header, prepended with the string specified in the setting
76
+ `JWT_AUTH_HEADER_PREFIX`. For example:
77
+
78
+ Authorization: JWT eyJhbGciOiAiSFMyNTYiLCAidHlwIj
79
+ """
80
+
81
+ www_authenticate_realm = "api"
82
+
83
+ def get_jwt_value(self, request: Request) -> int:
84
+ auth = get_authorization_header(request).split()
85
+ auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()
86
+
87
+ if not auth:
88
+ if api_settings.JWT_AUTH_COOKIE:
89
+ return request.COOKIES.get(api_settings.JWT_AUTH_COOKIE)
90
+ return None
91
+
92
+ if smart_str(auth[0].lower()) != auth_header_prefix:
93
+ return None
94
+
95
+ if len(auth) == 1:
96
+ msg = _("Invalid Authorization header. No credentials provided.")
97
+ raise exceptions.AuthenticationFailed(msg)
98
+ elif len(auth) > 2:
99
+ msg = _(
100
+ "Invalid Authorization header. Credentials string "
101
+ "should not contain spaces."
102
+ )
103
+ raise exceptions.AuthenticationFailed(msg)
104
+
105
+ return auth[1]
106
+
107
+ def authenticate_header(self, request: Request) -> str:
108
+ """
109
+ Return a string to be used as the value of the `WWW-Authenticate`
110
+ header in a `401 Unauthenticated` response, or `None` if the
111
+ authentication scheme should return `403 Permission Denied` responses.
112
+ """
113
+ return '{0} realm="{1}"'.format(
114
+ api_settings.JWT_AUTH_HEADER_PREFIX, self.www_authenticate_realm
115
+ )
@@ -0,0 +1,37 @@
1
+ from django.contrib.auth import get_user_model
2
+ from typing import Any, Dict
3
+
4
+ from rest_framework import serializers
5
+
6
+
7
+ class Serializer(serializers.Serializer):
8
+ @property
9
+ def object(self) -> Dict[str, Any]:
10
+ return self.validated_data
11
+
12
+
13
+ class PasswordField(serializers.CharField):
14
+ def __init__(self, *args, **kwargs):
15
+ if "style" not in kwargs:
16
+ kwargs["style"] = {"input_type": "password"}
17
+ else:
18
+ kwargs["style"]["input_type"] = "password"
19
+ super(PasswordField, self).__init__(*args, **kwargs)
20
+
21
+
22
+ def get_username_field() -> str:
23
+ try:
24
+ username_field = get_user_model().USERNAME_FIELD
25
+ except AttributeError:
26
+ username_field = "username"
27
+
28
+ return username_field
29
+
30
+
31
+ def get_username(user) -> str:
32
+ try:
33
+ username = user.get_username()
34
+ except AttributeError:
35
+ username = user.username
36
+
37
+ return username
@@ -0,0 +1,68 @@
1
+ # SOME DESCRIPTIVE TITLE.
2
+ # Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
3
+ # This file is distributed under the same license as the PACKAGE package.
4
+ # FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
5
+ #
6
+ #, fuzzy
7
+ msgid ""
8
+ msgstr ""
9
+ "Project-Id-Version: PACKAGE VERSION\n"
10
+ "Report-Msgid-Bugs-To: \n"
11
+ "POT-Creation-Date: 2015-03-01 21:35+0100\n"
12
+ "PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
13
+ "Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
14
+ "Language-Team: LANGUAGE <LL@li.org>\n"
15
+ "Language: \n"
16
+ "MIME-Version: 1.0\n"
17
+ "Content-Type: text/plain; charset=UTF-8\n"
18
+ "Content-Transfer-Encoding: 8bit\n"
19
+
20
+ #: authentication.py:33 serializers.py:100
21
+ msgid "Signature has expired."
22
+ msgstr ""
23
+
24
+ #: authentication.py:36 serializers.py:103
25
+ msgid "Error decoding signature."
26
+ msgstr ""
27
+
28
+ #: authentication.py:55
29
+ msgid "Invalid signature."
30
+ msgstr ""
31
+
32
+ #: authentication.py:58 serializers.py:117
33
+ msgid "Invalid payload."
34
+ msgstr ""
35
+
36
+ #: authentication.py:82
37
+ msgid "Invalid Authorization header. No credentials provided."
38
+ msgstr ""
39
+
40
+ #: authentication.py:85
41
+ msgid ""
42
+ "Invalid Authorization header. Credentials string should not contain spaces."
43
+ msgstr ""
44
+
45
+ #: serializers.py:59
46
+ msgid "User account is disabled."
47
+ msgstr ""
48
+
49
+ #: serializers.py:76
50
+ msgid "Unable to log in with provided credentials."
51
+ msgstr ""
52
+
53
+ #: serializers.py:79
54
+ #, python-brace-format
55
+ msgid "Must include \"{username_field}\" and \"password\"."
56
+ msgstr ""
57
+
58
+ #: serializers.py:120
59
+ msgid "User doesn't exist."
60
+ msgstr ""
61
+
62
+ #: serializers.py:170
63
+ msgid "Refresh has expired."
64
+ msgstr ""
65
+
66
+ #: serializers.py:173
67
+ msgid "orig_iat field is required."
68
+ msgstr ""
@@ -0,0 +1 @@
1
+ # Just to keep things like ./manage.py test happy
@@ -0,0 +1,166 @@
1
+ import jwt
2
+
3
+ from abc import abstractmethod
4
+ from calendar import timegm
5
+ from datetime import datetime, timedelta
6
+ from django.contrib.auth import authenticate, get_user_model
7
+ from django.utils.translation import gettext as _
8
+ from rest_framework import serializers
9
+ from typing import Any, Dict
10
+
11
+ from .compat import PasswordField, Serializer, get_username_field
12
+
13
+ from rest_framework_jwt.settings import api_settings
14
+
15
+
16
+ User = get_user_model()
17
+ jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
18
+ jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
19
+ jwt_decode_handler = api_settings.JWT_DECODE_HANDLER
20
+ jwt_get_username_from_payload = api_settings.JWT_PAYLOAD_GET_USERNAME_HANDLER
21
+
22
+
23
+ class JSONWebTokenSerializer(Serializer):
24
+ """
25
+ Serializer class used to validate a username and password.
26
+
27
+ 'username' is identified by the custom UserModel.USERNAME_FIELD.
28
+
29
+ Returns a JSON Web Token that can be used to authenticate later calls.
30
+ """
31
+
32
+ def __init__(self, *args, **kwargs):
33
+ """
34
+ Dynamically add the USERNAME_FIELD to self.fields.
35
+ """
36
+ super(JSONWebTokenSerializer, self).__init__(*args, **kwargs)
37
+
38
+ self.fields[self.username_field] = serializers.CharField()
39
+ self.fields["password"] = PasswordField(write_only=True)
40
+
41
+ @property
42
+ def username_field(self) -> str:
43
+ return get_username_field()
44
+
45
+ def validate(self, attrs: Dict[str, Any]):
46
+ credentials = {
47
+ self.username_field: attrs.get(self.username_field),
48
+ "password": attrs.get("password"),
49
+ }
50
+
51
+ if all(credentials.values()):
52
+ user = authenticate(**credentials)
53
+
54
+ if user:
55
+ if not user.is_active:
56
+ msg = _("User account is disabled.")
57
+ raise serializers.ValidationError(msg)
58
+
59
+ payload = jwt_payload_handler(user)
60
+
61
+ return {"token": jwt_encode_handler(payload), "user": user}
62
+ else:
63
+ msg = _("Unable to log in with provided credentials.")
64
+ raise serializers.ValidationError(msg)
65
+ else:
66
+ msg = _('Must include "{username_field}" and "password".')
67
+ msg = msg.format(username_field=self.username_field)
68
+ raise serializers.ValidationError(msg)
69
+
70
+
71
+ class VerificationBaseSerializer(Serializer):
72
+ """
73
+ Abstract serializer used for verifying and refreshing JWTs.
74
+ """
75
+
76
+ token = serializers.CharField()
77
+
78
+ @abstractmethod
79
+ def validate(self, attrs: Dict[str, Any]) -> Dict[str, Any]:
80
+ raise NotImplementedError(
81
+ "Please define a validate method."
82
+ ) # pragma: no cover
83
+
84
+ def _check_payload(self, token: str) -> Dict[str, Any]:
85
+ # Check payload valid (based off of JSONWebTokenAuthentication,
86
+ # may want to refactor)
87
+ try:
88
+ payload = jwt_decode_handler(token)
89
+ except jwt.ExpiredSignature:
90
+ msg = _("Signature has expired.")
91
+ raise serializers.ValidationError(msg)
92
+ except jwt.DecodeError:
93
+ msg = _("Error decoding signature.")
94
+ raise serializers.ValidationError(msg)
95
+
96
+ return payload
97
+
98
+ def _check_user(self, payload: Dict[str, Any]) -> User:
99
+ username = jwt_get_username_from_payload(payload)
100
+
101
+ if not username:
102
+ msg = _("Invalid payload.")
103
+ raise serializers.ValidationError(msg)
104
+
105
+ # Make sure user exists
106
+ try:
107
+ user = User.objects.get_by_natural_key(username)
108
+ except User.DoesNotExist:
109
+ msg = _("User doesn't exist.")
110
+ raise serializers.ValidationError(msg)
111
+
112
+ if not user.is_active:
113
+ msg = _("User account is disabled.")
114
+ raise serializers.ValidationError(msg)
115
+
116
+ return user
117
+
118
+
119
+ class VerifyJSONWebTokenSerializer(VerificationBaseSerializer):
120
+ """
121
+ Check the veracity of an access token.
122
+ """
123
+
124
+ def validate(self, attrs: Dict[str, Any]) -> Dict[str, Any]:
125
+ token = attrs["token"]
126
+
127
+ payload = self._check_payload(token=token)
128
+ user = self._check_user(payload=payload)
129
+
130
+ return {"token": token, "user": user}
131
+
132
+
133
+ class RefreshJSONWebTokenSerializer(VerificationBaseSerializer):
134
+ """
135
+ Refresh an access token.
136
+ """
137
+
138
+ def validate(self, attrs: Dict[str, Any]) -> Dict[str, Any]:
139
+ token = attrs["token"]
140
+
141
+ payload = self._check_payload(token=token)
142
+ user = self._check_user(payload=payload)
143
+ # Get and check 'orig_iat'
144
+ orig_iat = payload.get("orig_iat")
145
+
146
+ if orig_iat:
147
+ # Verify expiration
148
+ refresh_limit = api_settings.JWT_REFRESH_EXPIRATION_DELTA
149
+
150
+ if isinstance(refresh_limit, timedelta):
151
+ refresh_limit = refresh_limit.days * 24 * 3600 + refresh_limit.seconds
152
+
153
+ expiration_timestamp = orig_iat + int(refresh_limit)
154
+ now_timestamp = timegm(datetime.utcnow().utctimetuple())
155
+
156
+ if now_timestamp > expiration_timestamp:
157
+ msg = _("Refresh has expired.")
158
+ raise serializers.ValidationError(msg)
159
+ else:
160
+ msg = _("orig_iat field is required.")
161
+ raise serializers.ValidationError(msg)
162
+
163
+ new_payload = jwt_payload_handler(user)
164
+ new_payload["orig_iat"] = orig_iat
165
+
166
+ return {"token": jwt_encode_handler(new_payload), "user": user}
@@ -0,0 +1,44 @@
1
+ import datetime
2
+
3
+ from django.conf import settings
4
+ from rest_framework.settings import APISettings
5
+
6
+
7
+ USER_SETTINGS = getattr(settings, "JWT_AUTH", None)
8
+
9
+ DEFAULTS = {
10
+ "JWT_ENCODE_HANDLER": "rest_framework_jwt.utils.jwt_encode_handler",
11
+ "JWT_DECODE_HANDLER": "rest_framework_jwt.utils.jwt_decode_handler",
12
+ "JWT_PAYLOAD_HANDLER": "rest_framework_jwt.utils.jwt_payload_handler",
13
+ "JWT_PAYLOAD_GET_USER_ID_HANDLER": "rest_framework_jwt.utils.jwt_get_user_id_from_payload_handler",
14
+ "JWT_PRIVATE_KEY": None,
15
+ "JWT_PUBLIC_KEY": None,
16
+ "JWT_PAYLOAD_GET_USERNAME_HANDLER": "rest_framework_jwt.utils.jwt_get_username_from_payload_handler",
17
+ "JWT_RESPONSE_PAYLOAD_HANDLER": "rest_framework_jwt.utils.jwt_response_payload_handler",
18
+ "JWT_SECRET_KEY": settings.SECRET_KEY,
19
+ "JWT_GET_USER_SECRET_KEY": None,
20
+ "JWT_ALGORITHM": "HS256",
21
+ "JWT_VERIFY": True,
22
+ "JWT_VERIFY_EXPIRATION": True,
23
+ "JWT_LEEWAY": 0,
24
+ "JWT_EXPIRATION_DELTA": datetime.timedelta(seconds=300),
25
+ "JWT_AUDIENCE": None,
26
+ "JWT_ISSUER": None,
27
+ "JWT_ALLOW_REFRESH": False,
28
+ "JWT_REFRESH_EXPIRATION_DELTA": datetime.timedelta(days=7),
29
+ "JWT_AUTH_HEADER_PREFIX": "JWT",
30
+ "JWT_AUTH_COOKIE": None,
31
+ }
32
+
33
+ # List of settings that may be in string import notation.
34
+ IMPORT_STRINGS = (
35
+ "JWT_ENCODE_HANDLER",
36
+ "JWT_DECODE_HANDLER",
37
+ "JWT_PAYLOAD_HANDLER",
38
+ "JWT_PAYLOAD_GET_USER_ID_HANDLER",
39
+ "JWT_PAYLOAD_GET_USERNAME_HANDLER",
40
+ "JWT_RESPONSE_PAYLOAD_HANDLER",
41
+ "JWT_GET_USER_SECRET_KEY",
42
+ )
43
+
44
+ api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS)
@@ -0,0 +1,27 @@
1
+ from rest_framework.test import APITestCase, APIClient
2
+ from rest_framework import status
3
+ from rest_framework_jwt.settings import api_settings
4
+
5
+
6
+ class APIJWTClient(APIClient):
7
+ def login(self, **credentials):
8
+ """
9
+ Returns True if login is possible; False if the provided credentials
10
+ are incorrect, or the user is inactive.
11
+ """
12
+
13
+ response = self.post("/api-token-auth/", credentials, format="json")
14
+ if response.status_code == status.HTTP_200_OK:
15
+ self.credentials(
16
+ HTTP_AUTHORIZATION="{0} {1}".format(
17
+ api_settings.JWT_AUTH_HEADER_PREFIX, response.data["token"]
18
+ )
19
+ )
20
+
21
+ return True
22
+ else:
23
+ return False
24
+
25
+
26
+ class APIJWTTestCase(APITestCase):
27
+ client_class = APIJWTClient
@@ -0,0 +1,131 @@
1
+ import jwt
2
+ import uuid
3
+ import warnings
4
+
5
+ from calendar import timegm
6
+ from datetime import datetime
7
+ from django.contrib.auth import get_user_model
8
+ from django.contrib.auth.models import User
9
+ from rest_framework.request import Request
10
+ from typing import Any, Dict, Optional
11
+
12
+ from rest_framework_jwt.compat import get_username
13
+ from rest_framework_jwt.compat import get_username_field
14
+ from rest_framework_jwt.settings import api_settings
15
+
16
+
17
+ def jwt_get_secret_key(payload: Optional[Dict[str, Any]] = None) -> str:
18
+ """
19
+ For enhanced security you may want to use a secret key based on user.
20
+
21
+ This way you have an option to logout only this user if:
22
+ - token is compromised
23
+ - password is changed
24
+ - etc.
25
+ """
26
+ if api_settings.JWT_GET_USER_SECRET_KEY:
27
+ User = get_user_model() # noqa: N806
28
+ user = User.objects.get(pk=payload.get("user_id"))
29
+ key = str(api_settings.JWT_GET_USER_SECRET_KEY(user))
30
+ return key
31
+ return api_settings.JWT_SECRET_KEY
32
+
33
+
34
+ def jwt_payload_handler(user: User) -> Dict[str, Any]:
35
+ username_field = get_username_field()
36
+ username = get_username(user)
37
+
38
+ warnings.warn(
39
+ "The following fields will be removed in the future: "
40
+ "`email` and `user_id`. ",
41
+ DeprecationWarning,
42
+ )
43
+
44
+ payload = {
45
+ "user_id": user.pk,
46
+ "username": username,
47
+ "exp": datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA,
48
+ }
49
+ if hasattr(user, "email"):
50
+ payload["email"] = user.email
51
+ if isinstance(user.pk, uuid.UUID):
52
+ payload["user_id"] = str(user.pk)
53
+
54
+ payload[username_field] = username
55
+
56
+ # Include original issued at time for a brand new token,
57
+ # to allow token refresh
58
+ if api_settings.JWT_ALLOW_REFRESH:
59
+ payload["orig_iat"] = timegm(datetime.utcnow().utctimetuple())
60
+
61
+ if api_settings.JWT_AUDIENCE is not None:
62
+ payload["aud"] = api_settings.JWT_AUDIENCE
63
+
64
+ if api_settings.JWT_ISSUER is not None:
65
+ payload["iss"] = api_settings.JWT_ISSUER
66
+
67
+ return payload
68
+
69
+
70
+ def jwt_get_user_id_from_payload_handler(payload: Dict[str, Any]) -> Any:
71
+ """
72
+ Override this function if user_id is formatted differently in payload
73
+ """
74
+ warnings.warn(
75
+ "The following will be removed in the future. "
76
+ "Use `JWT_PAYLOAD_GET_USERNAME_HANDLER` instead.",
77
+ DeprecationWarning,
78
+ )
79
+
80
+ return payload.get("user_id")
81
+
82
+
83
+ def jwt_get_username_from_payload_handler(payload: Dict[str, Any]) -> str:
84
+ """
85
+ Override this function if username is formatted differently in payload
86
+ """
87
+ return payload.get("username")
88
+
89
+
90
+ def jwt_encode_handler(payload: Dict[str, Any]) -> bytes:
91
+ key = api_settings.JWT_PRIVATE_KEY or jwt_get_secret_key(payload)
92
+ return jwt.encode(payload, key, api_settings.JWT_ALGORITHM).decode("utf-8")
93
+
94
+
95
+ def jwt_decode_handler(token: str) -> Any:
96
+ options = {
97
+ "verify_exp": api_settings.JWT_VERIFY_EXPIRATION,
98
+ }
99
+ # get user from token, BEFORE verification, to get user secret key
100
+ unverified_payload = jwt.decode(token, None, False)
101
+ secret_key = jwt_get_secret_key(unverified_payload)
102
+ return jwt.decode(
103
+ token,
104
+ api_settings.JWT_PUBLIC_KEY or secret_key,
105
+ api_settings.JWT_VERIFY,
106
+ options=options,
107
+ leeway=api_settings.JWT_LEEWAY,
108
+ audience=api_settings.JWT_AUDIENCE,
109
+ issuer=api_settings.JWT_ISSUER,
110
+ algorithms=[api_settings.JWT_ALGORITHM],
111
+ )
112
+
113
+
114
+ def jwt_response_payload_handler(
115
+ token: str, user: Optional[User] = None, request: Optional[Request] = None
116
+ ):
117
+ """
118
+ Returns the response data for both the login and refresh views.
119
+ Override to return a custom response such as including the
120
+ serialized representation of the User.
121
+
122
+ Example:
123
+
124
+ def jwt_response_payload_handler(token, user=None, request=None):
125
+ return {
126
+ 'token': token,
127
+ 'user': UserSerializer(user, context={'request': request}).data
128
+ }
129
+
130
+ """
131
+ return {"token": token}
@@ -0,0 +1,113 @@
1
+ from datetime import datetime
2
+ from rest_framework.views import APIView
3
+ from rest_framework import status
4
+ from rest_framework.request import Request
5
+ from rest_framework.response import Response
6
+ from rest_framework.serializers import Serializer
7
+ from typing import Any, Dict, Type
8
+
9
+ from .settings import api_settings
10
+ from .serializers import (
11
+ JSONWebTokenSerializer,
12
+ RefreshJSONWebTokenSerializer,
13
+ VerifyJSONWebTokenSerializer,
14
+ )
15
+
16
+ jwt_response_payload_handler = api_settings.JWT_RESPONSE_PAYLOAD_HANDLER
17
+
18
+
19
+ class JSONWebTokenAPIView(APIView):
20
+ """
21
+ Base API View that various JWT interactions inherit from.
22
+ """
23
+
24
+ permission_classes = ()
25
+ authentication_classes = ()
26
+
27
+ def get_serializer_context(self) -> Dict[str, Any]:
28
+ """
29
+ Extra context provided to the serializer class.
30
+ """
31
+ return {
32
+ "request": self.request,
33
+ "view": self,
34
+ }
35
+
36
+ def get_serializer_class(self) -> Type[Serializer]:
37
+ """
38
+ Return the class to use for the serializer.
39
+ Defaults to using `self.serializer_class`.
40
+ You may want to override this if you need to provide different
41
+ serializations depending on the incoming request.
42
+ (Eg. admins get full serialization, others get basic serialization)
43
+ """
44
+ assert self.serializer_class is not None, (
45
+ "'%s' should either include a `serializer_class` attribute, "
46
+ "or override the `get_serializer_class()` method." % self.__class__.__name__
47
+ )
48
+ return self.serializer_class
49
+
50
+ def get_serializer(self, *args, **kwargs) -> Serializer:
51
+ """
52
+ Return the serializer instance that should be used for validating and
53
+ deserializing input, and for serializing output.
54
+ """
55
+ serializer_class = self.get_serializer_class()
56
+ kwargs["context"] = self.get_serializer_context()
57
+ return serializer_class(*args, **kwargs)
58
+
59
+ def post(self, request: Request, *args, **kwargs) -> Response:
60
+ serializer = self.get_serializer(data=request.data)
61
+
62
+ if serializer.is_valid():
63
+ user = serializer.object.get("user") or request.user
64
+ token = serializer.object.get("token")
65
+ response_data = jwt_response_payload_handler(token, user, request)
66
+ response = Response(response_data)
67
+ if api_settings.JWT_AUTH_COOKIE:
68
+ expiration = datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA
69
+ response.set_cookie(
70
+ api_settings.JWT_AUTH_COOKIE,
71
+ token,
72
+ expires=expiration,
73
+ httponly=True,
74
+ )
75
+ return response
76
+
77
+ return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
78
+
79
+
80
+ class ObtainJSONWebToken(JSONWebTokenAPIView):
81
+ """
82
+ API View that receives a POST with a user's username and password.
83
+
84
+ Returns a JSON Web Token that can be used for authenticated requests.
85
+ """
86
+
87
+ serializer_class = JSONWebTokenSerializer
88
+
89
+
90
+ class VerifyJSONWebToken(JSONWebTokenAPIView):
91
+ """
92
+ API View that checks the veracity of a token, returning the token if it
93
+ is valid.
94
+ """
95
+
96
+ serializer_class = VerifyJSONWebTokenSerializer
97
+
98
+
99
+ class RefreshJSONWebToken(JSONWebTokenAPIView):
100
+ """
101
+ API View that returns a refreshed token (with new expiration) based on
102
+ existing token
103
+
104
+ If 'orig_iat' field (original issued-at-time) is found, will first check
105
+ if it's within expiration window, then copy it to the new token
106
+ """
107
+
108
+ serializer_class = RefreshJSONWebTokenSerializer
109
+
110
+
111
+ obtain_jwt_token = ObtainJSONWebToken.as_view()
112
+ refresh_jwt_token = RefreshJSONWebToken.as_view()
113
+ verify_jwt_token = VerifyJSONWebToken.as_view()