Public and private clients can now have different expiry times

Public clients often wish to have shorter expieration times
This commit is contained in:
Adam Charnock 2013-09-14 14:36:17 +01:00 committed by Evan Culver
parent 64609c0e33
commit 69a7c3e2e3
4 changed files with 21 additions and 4 deletions

View File

@ -24,6 +24,8 @@ DEFAULT_SCOPES = (
SCOPES = getattr(settings, 'OAUTH_SCOPES', DEFAULT_SCOPES)
EXPIRE_DELTA = getattr(settings, 'OAUTH_EXPIRE_DELTA', timedelta(days=365))
# Expiry delta for public clients (which typically have shorter lived tokens)
EXPIRE_DELTA_PUBLIC = getattr(settings, 'OAUTH_EXPIRE_DELTA_PUBLIC', timedelta(days=30))
EXPIRE_CODE_DELTA = getattr(settings, 'OAUTH_EXPIRE_CODE_DELTA', timedelta(seconds=10 * 60))

View File

@ -49,6 +49,10 @@ class Client(models.Model):
def __unicode__(self):
return self.redirect_uri
def get_default_token_expiry(self):
public = (self.client_type == 1)
return get_token_expiry(public)
class Grant(models.Model):
"""
@ -100,7 +104,7 @@ class AccessToken(models.Model):
user = models.ForeignKey(AUTH_USER_MODEL)
token = models.CharField(max_length=255, default=long_token)
client = models.ForeignKey(Client)
expires = models.DateTimeField(default=get_token_expiry)
expires = models.DateTimeField()
scope = models.IntegerField(default=constants.SCOPES[0][0],
choices=constants.SCOPES)
@ -109,6 +113,11 @@ class AccessToken(models.Model):
def __unicode__(self):
return self.token
def save(self, *args, **kwargs):
if not self.expires:
self.expires = self.client.get_default_token_expiry()
super(AccessToken, self).save(*args, **kwargs)
def get_expire_delta(self, reference=None):
"""
Return the number of seconds until this token expires.

View File

@ -349,6 +349,9 @@ class AccessTokenTest(BaseOAuth2TestCase):
self.assertEqual(200, response.status_code, response.content)
self.assertNotIn('refresh_token', json.loads(response.content))
expires_in = json.loads(response.content)['expires_in']
expires_in_days = round(expires_in / (60.0 * 60.0 * 24.0))
self.assertEqual(expires_in_days, constants.EXPIRE_DELTA_PUBLIC.days)
def test_password_grant_confidential(self):
c = self.get_client()

View File

@ -2,7 +2,7 @@ import hashlib
import shortuuid
from datetime import datetime, tzinfo
from django.conf import settings
from .constants import EXPIRE_DELTA, EXPIRE_CODE_DELTA
from .constants import EXPIRE_DELTA, EXPIRE_DELTA_PUBLIC, EXPIRE_CODE_DELTA
try:
from django.utils import timezone
@ -35,13 +35,16 @@ def long_token():
return hash.hexdigest()
def get_token_expiry():
def get_token_expiry(public=True):
"""
Return a datetime object indicating when an access token should expire.
Can be customized by setting :attr:`settings.OAUTH_EXPIRE_DELTA` to a
:attr:`datetime.timedelta` object.
"""
return now() + EXPIRE_DELTA
if public:
return now() + EXPIRE_DELTA_PUBLIC
else:
return now() + EXPIRE_DELTA
def get_code_expiry():