diff --git a/rest_framework_simplejwt/models.py b/rest_framework_simplejwt/models.py index 234de73e3..4483dbf5c 100644 --- a/rest_framework_simplejwt/models.py +++ b/rest_framework_simplejwt/models.py @@ -106,4 +106,6 @@ def get_username(self): def __getattr__(self, attr): """This acts as a backup attribute getter for custom claims defined in Token serializers.""" - return self.token.get(attr, None) + if attr in self.token: + return self.token[attr] + raise AttributeError(f"'TokenUser' does not have an attribute {attr}") diff --git a/tests/test_models.py b/tests/test_models.py index 3a017fbfe..cabdb337c 100644 --- a/tests/test_models.py +++ b/tests/test_models.py @@ -1,3 +1,4 @@ +import pytest from django.test import TestCase from rest_framework_simplejwt.models import TokenUser @@ -105,3 +106,13 @@ def test_is_authenticated(self): def test_get_username(self): self.assertEqual(self.user.get_username(), "deep-thought") + + def test_getattr_returns_token_data(self): + self.assertEqual(self.user.__getattr__("some_other_stuff"), "arstarst") + + def test_getattr_raises_attribute_error(self): + with pytest.raises(AttributeError): + self.user.__getattr__("_not_an_attribute") + + def test_hasattr_for_missing_attribute(self): + self.assertFalse(hasattr(self.user, "_not_an_attribute"))