Skip to content
This repository has been archived by the owner on May 26, 2020. It is now read-only.

Commit

Permalink
Merge pull request #268 from shanx/allow-user-without-email
Browse files Browse the repository at this point in the history
Allow jtw_payload_handler to work with User models that don't have an Email field
  • Loading branch information
angvp authored May 5, 2017
2 parents 160aaeb + 5a369c4 commit 8bf295c
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 1 deletion.
3 changes: 2 additions & 1 deletion rest_framework_jwt/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,11 @@ def jwt_payload_handler(user):

payload = {
'user_id': user.pk,
'email': user.email,
'username': username,
'exp': datetime.utcnow() + api_settings.JWT_EXPIRATION_DELTA
}
if hasattr(user, 'email'):
payload['email'] = user.email
if isinstance(user.pk, uuid.UUID):
payload['user_id'] = str(user.pk)

Expand Down
11 changes: 11 additions & 0 deletions tests/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,17 @@ class Meta:
app_label = 'tests'


class CustomUserWithoutEmail(AbstractBaseUser):
username = models.CharField(max_length=255, unique=True)

objects = BaseUserManager()

USERNAME_FIELD = 'username'

class Meta:
app_label = 'tests'


class CustomUserUUID(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(max_length=255, unique=True)
Expand Down
11 changes: 11 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from rest_framework_jwt import utils
from rest_framework_jwt.compat import get_user_model
from rest_framework_jwt.settings import api_settings, DEFAULTS
from tests.models import CustomUserWithoutEmail

User = get_user_model()

Expand Down Expand Up @@ -38,6 +39,16 @@ def test_jwt_payload_handler(self):
self.assertEqual(payload['username'], self.username)
self.assertTrue('exp' in payload)

def test_jwt_payload_handler_no_email_address(self):
user = CustomUserWithoutEmail.objects.create(username=self.username)

payload = utils.jwt_payload_handler(user)
self.assertTrue(isinstance(payload, dict))
self.assertFalse(hasattr(payload, 'email'))
self.assertEqual(payload['user_id'], self.user.pk)
self.assertEqual(payload['username'], self.username)
self.assertTrue('exp' in payload)

def test_jwt_encode(self):
payload = utils.jwt_payload_handler(self.user)
token = utils.jwt_encode_handler(payload)
Expand Down

0 comments on commit 8bf295c

Please sign in to comment.