Skip to content

Commit cd46299

Browse files
trbssynasius
authored andcommitted
Issue #148 cleanup of expired tokens
Simple implementation of cleanup strategy for expired tokens.
1 parent e8e3af2 commit cd46299

File tree

5 files changed

+26
-1
lines changed

5 files changed

+26
-1
lines changed

oauth2_provider/management/__init__.py

Whitespace-only changes.

oauth2_provider/management/commands/__init__.py

Whitespace-only changes.
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
from django.core.management.base import BaseCommand, CommandError
2+
from ...models import clear_expired
3+
4+
5+
class Command(BaseCommand):
6+
help = "Can be run as a cronjob or directly to clean out expired tokens"
7+
8+
def handle(self, *args, **options):
9+
clear_expired()

oauth2_provider/models.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
from __future__ import unicode_literals
22

3+
from datetime import timedelta
4+
35
from django.core.urlresolvers import reverse
4-
from django.db import models
6+
from django.db import models, transaction
57
from django.utils import timezone
68

79
from django.utils.translation import ugettext_lazy as _
@@ -266,3 +268,16 @@ def get_application_model():
266268
e = "APPLICATION_MODEL refers to model {0} that has not been installed"
267269
raise ImproperlyConfigured(e.format(oauth2_settings.APPLICATION_MODEL))
268270
return app_model
271+
272+
273+
def clear_expired():
274+
REFRESH_TOKEN_EXPIRE_SECONDS = oauth2_settings.REFRESH_TOKEN_EXPIRE_SECONDS
275+
if not isinstance(REFRESH_TOKEN_EXPIRE_SECONDS, timedelta):
276+
REFRESH_TOKEN_EXPIRE_SECONDS = timedelta(seconds=REFRESH_TOKEN_EXPIRE_SECONDS)
277+
now = timezone.now()
278+
with transaction.atomic():
279+
if REFRESH_TOKEN_EXPIRE_SECONDS:
280+
refresh_expire_date = now - REFRESH_TOKEN_EXPIRE_SECONDS
281+
RefreshToken.objects.filter(access_token__expires__lt=refresh_expire_date).delete()
282+
AccessToken.objects.filter(refresh_token__isnull=True, expires__lt=now).delete()
283+
Grant.objects.filter(expires__lt=now).delete()

oauth2_provider/settings.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@
4141
'WRITE_SCOPE': 'write',
4242
'AUTHORIZATION_CODE_EXPIRE_SECONDS': 60,
4343
'ACCESS_TOKEN_EXPIRE_SECONDS': 36000,
44+
'REFRESH_TOKEN_EXPIRE_SECONDS': None,
4445
'APPLICATION_MODEL': getattr(settings, 'OAUTH2_PROVIDER_APPLICATION_MODEL', 'oauth2_provider.Application'),
4546
'REQUEST_APPROVAL_PROMPT': 'force',
4647
'ALLOWED_REDIRECT_URI_SCHEMES': ['http', 'https'],

0 commit comments

Comments
 (0)