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
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
This allows for a client to request refresh tokens. These refresh tokens do not expire. They can be revoked (deleted). When a JWT has expired, it's possible to send a request with the refresh token in the header, and get back a new JWT. This allows for the client to not have to store username/passwords. So, if the client gets a responce about an expired token the client can automatically make a call (behind the scenes) to delegate a new JWT using the stored refresh token. Thus keeping the 'session' active. moving everything to it's own sub dir, so that the refresh token functionality can be optionally installed.
- Loading branch information
Showing
11 changed files
with
336 additions
and
9 deletions.
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
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,40 @@ | ||
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, unique=True) | ||
created = models.DateTimeField(auto_now_add=True) | ||
|
||
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, DelagateJSONWebToken | ||
|
||
router = routers.SimpleRouter() | ||
router.register(r'refresh-token', RefreshTokenViewSet) | ||
|
||
urlpatterns = router.urls + patterns('', # NOQA | ||
url(r'delgate/$', DelagateJSONWebToken.as_view(), name='delgate-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,17 @@ | ||
from .models import RefreshToken | ||
from rest_framework import serializers | ||
|
||
|
||
class RefreshTokenSerializer(serializers.ModelSerializer): | ||
""" | ||
Serializer for refresh tokens (Not RefreshJWTToken) | ||
""" | ||
|
||
class Meta: | ||
model = RefreshToken | ||
fields = ('key', 'user', 'created', 'app') | ||
read_only_fields = ('key', 'user', 'created') | ||
|
||
def validate(self, attrs): | ||
attrs['user'] = self.context['request'].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,65 @@ | ||
from calendar import timegm | ||
from datetime import datetime | ||
|
||
from rest_framework import mixins | ||
from rest_framework import viewsets | ||
from rest_framework.response import Response | ||
from rest_framework import status | ||
from rest_framework import parsers | ||
from rest_framework import renderers | ||
|
||
from rest_framework_jwt.settings import api_settings | ||
from rest_framework_jwt.views import JSONWebTokenAPIView | ||
from rest_framework_jwt.authentication import RefreshTokenAuthentication | ||
|
||
from .permissions import IsOwnerOrAdmin | ||
from .models import RefreshToken | ||
from .serializers import RefreshTokenSerializer | ||
|
||
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER | ||
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER | ||
|
||
|
||
class DelagateJSONWebToken(JSONWebTokenAPIView): | ||
""" | ||
API View that checks the veracity of a refresh token, returning a JWT if it | ||
is valid. | ||
""" | ||
authentication_classes = (RefreshTokenAuthentication, ) | ||
|
||
def post(self, request): | ||
user = request.user | ||
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 | ||
""" | ||
throttle_classes = () | ||
authentication_classes = () | ||
parser_classes = (parsers.FormParser, parsers.JSONParser,) | ||
renderer_classes = (renderers.JSONRenderer,) | ||
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
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.