This repository has been archived by the owner on May 26, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 651
Long running refresh tokens #123
Closed
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ef517c8
Long running refresh tokens
fxdgear ca84a6f
fixing typos, removing some viewset overrides
fxdgear b0b7570
Make refreshtoken a separate app.
ticosax 80e5b7c
Remove unicity constraint on app field
ticosax d0cedd1
Be compliant with https://auth0.com/docs/refresh-token
ticosax File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Empty file.
24 changes: 24 additions & 0 deletions
24
rest_framework_jwt/refreshtoken/migrations/0001_initial.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# -*- coding: utf-8 -*- | ||
from __future__ import unicode_literals | ||
|
||
from django.db import models, migrations | ||
from django.conf import settings | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
migrations.swappable_dependency(settings.AUTH_USER_MODEL), | ||
] | ||
|
||
operations = [ | ||
migrations.CreateModel( | ||
name='RefreshToken', | ||
fields=[ | ||
('key', models.CharField(max_length=40, primary_key=True, serialize=False)), | ||
('app', models.CharField(unique=True, max_length=255)), | ||
('created', models.DateTimeField(auto_now_add=True)), | ||
('user', models.ForeignKey(related_name='refresh_tokens', to=settings.AUTH_USER_MODEL)), | ||
], | ||
), | ||
] |
23 changes: 23 additions & 0 deletions
23
rest_framework_jwt/refreshtoken/migrations/0002_auto_20150515_0948.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# -*- coding: utf-8 -*- | ||
from __future__ import unicode_literals | ||
|
||
from django.db import models, migrations | ||
|
||
|
||
class Migration(migrations.Migration): | ||
|
||
dependencies = [ | ||
('refreshtoken', '0001_initial'), | ||
] | ||
|
||
operations = [ | ||
migrations.AlterField( | ||
model_name='refreshtoken', | ||
name='app', | ||
field=models.CharField(max_length=255), | ||
), | ||
migrations.AlterUniqueTogether( | ||
name='refreshtoken', | ||
unique_together=set([('user', 'app')]), | ||
), | ||
] |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import binascii | ||
import os | ||
|
||
from django.conf import settings | ||
from django.db import models | ||
from django.utils.encoding import python_2_unicode_compatible | ||
|
||
|
||
# Prior to Django 1.5, the AUTH_USER_MODEL setting does not exist. | ||
# Note that we don't perform this code in the compat module due to | ||
# bug report #1297 | ||
# See: https://github.com/tomchristie/django-rest-framework/issues/1297 | ||
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') | ||
|
||
|
||
@python_2_unicode_compatible | ||
class RefreshToken(models.Model): | ||
""" | ||
Copied from | ||
https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/authtoken/models.py | ||
Wanted to only change the user relation to be a "ForeignKey" instead of a OneToOneField | ||
|
||
The `ForeignKey` value allows us to create multiple RefreshTokens per user | ||
|
||
""" | ||
key = models.CharField(max_length=40, primary_key=True) | ||
user = models.ForeignKey(AUTH_USER_MODEL, related_name='refresh_tokens') | ||
app = models.CharField(max_length=255) | ||
created = models.DateTimeField(auto_now_add=True) | ||
|
||
class Meta: | ||
unique_together = ('user', 'app') | ||
|
||
def save(self, *args, **kwargs): | ||
if not self.key: | ||
self.key = self.generate_key() | ||
return super(RefreshToken, self).save(*args, **kwargs) | ||
|
||
def generate_key(self): | ||
return binascii.hexlify(os.urandom(20)).decode() | ||
|
||
def __str__(self): | ||
return self.key |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
from rest_framework import permissions | ||
|
||
|
||
class IsOwnerOrAdmin(permissions.BasePermission): | ||
""" | ||
Only admins or owners can have permission | ||
""" | ||
def has_permission(self, request, view): | ||
return request.user and request.user.is_authenticated() | ||
|
||
def has_object_permission(self, request, view, obj): | ||
""" | ||
If user is staff or superuser or 'owner' of object return True | ||
Else return false. | ||
""" | ||
if not request.user.is_authenticated(): | ||
return False | ||
elif request.user.is_staff or request.user.is_superuser: | ||
return True | ||
else: | ||
return request.user == obj.user |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,11 @@ | ||
from rest_framework import routers | ||
from django.conf.urls import patterns, url | ||
|
||
from .views import RefreshTokenViewSet, DelegateJSONWebToken | ||
|
||
router = routers.SimpleRouter() | ||
router.register(r'refresh-token', RefreshTokenViewSet) | ||
|
||
urlpatterns = router.urls + patterns('', # NOQA | ||
url(r'^delegate/$', DelegateJSONWebToken.as_view(), name='delegate-tokens'), | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
from django.utils.translation import ugettext as _ | ||
from rest_framework import exceptions | ||
from rest_framework import serializers | ||
from rest_framework_jwt.compat import CurrentUserDefault, Serializer | ||
|
||
from .models import RefreshToken | ||
|
||
|
||
class RefreshTokenSerializer(serializers.ModelSerializer): | ||
""" | ||
Serializer for refresh tokens (Not RefreshJWTToken) | ||
""" | ||
|
||
user = serializers.PrimaryKeyRelatedField( | ||
required=False, | ||
read_only=True, | ||
default=CurrentUserDefault()) | ||
|
||
class Meta: | ||
model = RefreshToken | ||
fields = ('key', 'user', 'created', 'app') | ||
read_only_fields = ('key', 'created') | ||
|
||
def validate(self, attrs): | ||
""" | ||
only for DRF < 3.0 support. | ||
Otherwise CurrentUserDefault() is doing the job of obtaining user | ||
from current request. | ||
""" | ||
if 'user' not in attrs: | ||
attrs['user'] = self.context['request'].user | ||
return attrs | ||
|
||
|
||
class DelegateJSONWebTokenSerializer(Serializer): | ||
client_id = serializers.CharField() | ||
grant_type = serializers.CharField( | ||
default='urn:ietf:params:oauth:grant-type:jwt-bearer', | ||
required=False, | ||
) | ||
refresh_token = serializers.CharField() | ||
api_type = serializers.CharField( | ||
default='app', | ||
required=False, | ||
) | ||
|
||
def validate(self, attrs): | ||
refresh_token = attrs['refresh_token'] | ||
try: | ||
token = RefreshToken.objects.select_related('user').get( | ||
key=refresh_token) | ||
except RefreshToken.DoesNotExist: | ||
raise exceptions.AuthenticationFailed(_('Invalid token.')) | ||
attrs['user'] = token.user | ||
return attrs |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
from calendar import timegm | ||
from datetime import datetime | ||
|
||
from django.utils.translation import ugettext as _ | ||
from rest_framework import exceptions | ||
from rest_framework import generics | ||
from rest_framework import mixins | ||
from rest_framework import viewsets | ||
from rest_framework.response import Response | ||
from rest_framework import status | ||
|
||
from rest_framework_jwt.settings import api_settings | ||
|
||
from .permissions import IsOwnerOrAdmin | ||
from .models import RefreshToken | ||
from .serializers import ( | ||
DelegateJSONWebTokenSerializer, | ||
RefreshTokenSerializer, | ||
) | ||
|
||
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER | ||
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER | ||
|
||
|
||
class DelegateJSONWebToken(generics.CreateAPIView): | ||
""" | ||
API View that checks the veracity of a refresh token, returning a JWT if it | ||
is valid. | ||
""" | ||
serializer_class = DelegateJSONWebTokenSerializer | ||
|
||
def post(self, request, *args, **kwargs): | ||
serializer = self.get_serializer(data=request.DATA) | ||
# pass raise_exception=True argument once we drop support | ||
# of DRF < 3.0 | ||
serializer.is_valid() | ||
if serializer.errors: | ||
return Response(serializer.errors, | ||
status=status.HTTP_400_BAD_REQUEST) | ||
user = serializer.object['user'] | ||
if not user.is_active: | ||
raise exceptions.AuthenticationFailed( | ||
_('User inactive or deleted.')) | ||
|
||
payload = jwt_payload_handler(user) | ||
if api_settings.JWT_ALLOW_REFRESH: | ||
payload['orig_iat'] = timegm(datetime.utcnow().utctimetuple()) | ||
return Response( | ||
{'token': jwt_encode_handler(payload)}, | ||
status=status.HTTP_201_CREATED | ||
) | ||
|
||
|
||
class RefreshTokenViewSet(mixins.RetrieveModelMixin, | ||
mixins.CreateModelMixin, | ||
mixins.DestroyModelMixin, | ||
mixins.ListModelMixin, | ||
viewsets.GenericViewSet): | ||
""" | ||
API View that will Create/Delete/List `RefreshToken`. | ||
|
||
https://auth0.com/docs/refresh-token | ||
""" | ||
permission_classes = (IsOwnerOrAdmin, ) | ||
serializer_class = RefreshTokenSerializer | ||
queryset = RefreshToken.objects.all() | ||
lookup_field = 'key' | ||
|
||
def get_queryset(self): | ||
queryset = super(RefreshTokenViewSet, self).get_queryset() | ||
if self.request.user.is_superuser or self.request.user.is_staff: | ||
return queryset | ||
else: | ||
return queryset.filter(user=self.request.user) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would probably be best to squash these migrations?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, but I would like to do it once @jpadilla considers it ready for merging. Just in case some amendments are still necessary on the Model.
I will add it in the description as a reminder.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
👍