Skip to content
This repository was archived by the owner on Aug 3, 2024. It is now read-only.

Commit 14d42b6

Browse files
committed
Added support for Django user without UUID field as user.id
1 parent 3353c74 commit 14d42b6

File tree

9 files changed

+72
-13
lines changed

9 files changed

+72
-13
lines changed

README.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,12 @@ urlpatterns = [
2828

2929
In Django settings, include the following:
3030
```python
31+
32+
INSTALLED_APPS = [
33+
...,
34+
'rest_framework_microservice',
35+
]
36+
3137
REST_FRAMEWORK = {
3238
'DEFAULT_AUTHENTICATION_CLASSES': (
3339
'rest_framework_simplejwt.authentication.JWTTokenUserAuthentication',
@@ -122,6 +128,7 @@ REST_FRAMEWORK_MICROSERVICE = {
122128
"CUSTOM_TOKEN_CALLABLE_ATTRIBUTES": [],
123129
"COOKIE_SALT": "extra",
124130
"USER_SERIALIZER_CLASS": None,
131+
"USER_MODEL_UUID_FIELD": None,
125132
}
126133
```
127134

@@ -170,6 +177,11 @@ Salt to be used when signing cookie.
170177
Defaults to None. If specified, the default view serializers will try to add a user object representing the user.
171178
The content of the user object is defined by ``USER_SERIALIZER_CLASS``.
172179

180+
``USER_MODEL_UUID_FIELD``
181+
-------------------------
182+
Defaults to None. Used to specify a field on the Django user model that can be used to store UUID from IDP.
183+
184+
173185
Customizing token claims
174186
========================
175187

make_package_migrations.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,12 +14,13 @@
1414
INSTALLED_APPS=(
1515
'django.contrib.contenttypes',
1616
'django.contrib.auth',
17-
'django_microservice',
17+
'rest_framework_microservice',
1818
),
19+
SECRET_KEY="NA"
1920
)
2021

2122
django.setup()
22-
call_command('makemigrations', )
23+
call_command('makemigrations', 'rest_framework_microservice')
2324

2425
print('''
2526
Finished generating migrations.

rest_framework_microservice/apps.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22

33

44
class RestFrameworkMicroserviceConfig(AppConfig):
5+
default_auto_field = 'django.db.models.BigAutoField'
56
name = 'rest_framework_microservice'
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Generated by Django 4.0.3 on 2022-04-04 00:00
2+
3+
from django.conf import settings
4+
from django.db import migrations, models
5+
import django.db.models.deletion
6+
7+
8+
class Migration(migrations.Migration):
9+
10+
initial = True
11+
12+
dependencies = [
13+
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
14+
]
15+
16+
operations = [
17+
migrations.CreateModel(
18+
name='Idp',
19+
fields=[
20+
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
21+
('uuid', models.UUIDField()),
22+
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='idp', to=settings.AUTH_USER_MODEL)),
23+
],
24+
),
25+
migrations.AddIndex(
26+
model_name='idp',
27+
index=models.Index(fields=['uuid'], name='rest_framew_uuid_a01bb5_idx'),
28+
),
29+
]

rest_framework_microservice/migrations/__init__.py

Whitespace-only changes.

rest_framework_microservice/models.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
11
from rest_framework_simplejwt.models import TokenUser
2+
from django.db import models
3+
from django.contrib.auth import get_user_model
4+
25

36
class CustomTokenUser(TokenUser):
47
"""
@@ -9,4 +12,12 @@ class CustomTokenUser(TokenUser):
912
# TODO: No longer needed in newer version of djangorestframework-simplejwt
1013
# See: https://github.com/jazzband/djangorestframework-simplejwt/pull/528
1114
def __getattr__(self, attr_name):
12-
return self.token.get(attr_name, None)
15+
return self.token.get(attr_name, None)
16+
17+
18+
class Idp(models.Model):
19+
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="idp")
20+
uuid = models.UUIDField()
21+
22+
class Meta:
23+
indexes = [models.Index(fields=['uuid'])]

rest_framework_microservice/serializers.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from django.core.exceptions import ObjectDoesNotExist
1616
from rest_framework.response import Response
1717
from .social_auth.aws_cognito import decode_token
18-
18+
from .models import Idp
1919

2020
def add_custom_token_claims(token, user):
2121
"""Append custom token claims specified using settings."""
@@ -145,15 +145,19 @@ def validate(self, attrs):
145145
if id_token.get('email_verified') is False:
146146
raise APIException("Email not verified.")
147147

148+
user_defaults = {
149+
"username": id_token["cognito:username"],
150+
"first_name": id_token.get("given_name"),
151+
"last_name": id_token.get("family_name"),
152+
}
153+
154+
if rest_microservice_settings.USER_MODEL_UUID_FIELD is not None:
155+
user_defaults[rest_microservice_settings.USER_MODEL_UUID_FIELD] = id_token['sub']
156+
157+
user, created = get_user_model().objects.get_or_create(email=id_token["email"], defaults=user_defaults)
148158

149-
user, created = get_user_model().objects.get_or_create(
150-
email=id_token["email"],
151-
defaults={
152-
"id": id_token['sub'],
153-
"username": id_token["cognito:username"],
154-
"first_name": id_token.get("given_name"),
155-
"last_name": id_token.get("family_name"),
156-
})
159+
if rest_microservice_settings.USER_MODEL_UUID_FIELD is None:
160+
Idp.objects.update_or_create(user=user, defaults={"uuid": id_token['sub']})
157161

158162
refresh = self.get_token(user)
159163
data = {

rest_framework_microservice/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
"CUSTOM_TOKEN_CALLABLE_ATTRIBUTES": [],
1818
"COOKIE_SALT": "extra",
1919
"USER_SERIALIZER_CLASS": None,
20+
"USER_MODEL_UUID_FIELD": None,
2021
}
2122

2223
IMPORT_STRINGS = [

setup.cfg

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[metadata]
22
name = django-rest-microservice
3-
version = 1.0.3
3+
version = 1.1
44
description = Facilitating microservice architecture in Django REST framework
55
long_description = file: README.md
66
url = https://github.com/oscarychen/django-rest-microservice

0 commit comments

Comments
 (0)