Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for custom functions for getting user object from user_id and vice versa #135

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,8 @@ Some of Simple JWT's behavior can be customized through settings variables in
'ALGORITHM': 'HS256',
'SIGNING_KEY': settings.SECRET_KEY,
'VERIFYING_KEY': None,
'USER_ID_TO_USER': None,
'USER_TO_USER_ID': None,
'AUDIENCE': None,
'ISSUER': None,

Expand Down Expand Up @@ -231,6 +233,16 @@ VERIFYING_KEY
by the ``ALGORITHM`` setting, the ``VERIFYING_KEY`` setting must be set to a
string which contains an RSA public key.

USER_ID_TO_USER
A function that will be called with the value of ``USER_ID_CLAIM`` when decoding a token.
It should return a user object or raise User.DoesNotExist. This lets you specify a custom
behaviour for user_id decoding and object instantiation.

USER_TO_USER_ID
A function that will be called with the user object when encoding a token. It should return
a user_id to be placed into ``USER_ID_CLAIM`` in the token. This lets you specify a custom
behaviour for generation of user_id for user object.

AUDIENCE
The audience claim to be included in generated tokens and/or validated in
decoded tokens. When set to ``None``, this field is excluded from tokens and
Expand Down
7 changes: 6 additions & 1 deletion rest_framework_simplejwt/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,12 @@ def get_user(self, validated_token):
raise InvalidToken(_('Token contained no recognizable user identification'))

try:
user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
if api_settings.USER_ID_TO_USER:
user = api_settings.USER_ID_TO_USER(user_id)
if not user:
raise User.DoesNotExist()
else:
user = User.objects.get(**{api_settings.USER_ID_FIELD: user_id})
except User.DoesNotExist:
raise AuthenticationFailed(_('User not found'), code='user_not_found')

Expand Down
4 changes: 4 additions & 0 deletions rest_framework_simplejwt/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
'VERIFYING_KEY': None,
'AUDIENCE': None,
'ISSUER': None,
'USER_ID_TO_USER': None,
'USER_TO_USER_ID': None,

'AUTH_HEADER_TYPES': ('Bearer',),
'USER_ID_FIELD': 'id',
Expand All @@ -37,6 +39,8 @@

IMPORT_STRINGS = (
'AUTH_TOKEN_CLASSES',
'USER_ID_TO_USER',
'USER_TO_USER_ID',
)

REMOVED_SETTINGS = (
Expand Down
5 changes: 4 additions & 1 deletion rest_framework_simplejwt/tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,10 @@ def for_user(cls, user):
Returns an authorization token for the given user that will be provided
after authenticating the user's credentials.
"""
user_id = getattr(user, api_settings.USER_ID_FIELD)
if api_settings.USER_TO_USER_ID:
user_id = api_settings.USER_TO_USER_ID(user)
else:
user_id = getattr(user, api_settings.USER_ID_FIELD)
if not isinstance(user_id, int):
user_id = str(user_id)

Expand Down
33 changes: 33 additions & 0 deletions tests/test_authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,15 @@
AuthToken = api_settings.AUTH_TOKEN_CLASSES[0]


def _user2userid(user):
return "CUSTOM_" + str(getattr(user, api_settings.USER_ID_FIELD))


def _userid2user(user_id):
user_id = int(str(user_id)[7:])
return User.objects.get(**{api_settings.USER_ID_FIELD: user_id})


class TestJWTAuthentication(TestCase):
def setUp(self):
self.factory = APIRequestFactory()
Expand Down Expand Up @@ -138,6 +147,30 @@ def test_get_user(self):
# Otherwise, should return correct user
self.assertEqual(self.backend.get_user(payload).id, u.id)

def test_user_id_to_user(self):
payload = {'some_other_id': 'foo'}

with override_api_settings(USER_ID_TO_USER=_userid2user):
# Should raise error if no recognizable user identification
with self.assertRaises(InvalidToken):
self.backend.get_user(payload)

u = User.objects.create_user(username='markhamill')
u.is_active = False
u.save()

payload[api_settings.USER_ID_CLAIM] = _user2userid(u)

# Should raise exception if user is inactive
with self.assertRaises(AuthenticationFailed):
self.backend.get_user(payload)

u.is_active = True
u.save()

# Otherwise, should return correct user
self.assertEqual(self.backend.get_user(payload).id, u.id)


class TestJWTTokenUserAuthentication(TestCase):
def setUp(self):
Expand Down
18 changes: 18 additions & 0 deletions tests/test_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ class MyToken(Token):
lifetime = timedelta(days=1)


def _user2userid(user):
return "CUSTOM_" + str(getattr(user, api_settings.USER_ID_FIELD))


class TestToken(TestCase):
def setUp(self):
self.token = MyToken()
Expand Down Expand Up @@ -299,6 +303,20 @@ def test_for_user(self):

self.assertEqual(token[api_settings.USER_ID_CLAIM], username)

def test_user_to_user_id(self):
username = 'test_user'
user = User.objects.create_user(
username=username,
password='test_password',
)

with override_api_settings(USER_TO_USER_ID=_user2userid):
token = MyToken.for_user(user)

user_id = _user2userid(user)

self.assertEqual(token[api_settings.USER_ID_CLAIM], user_id)


class TestSlidingToken(TestCase):
def test_init(self):
Expand Down