Skip to content

Commit

Permalink
Add elongate_odk_token management command
Browse files Browse the repository at this point in the history
  • Loading branch information
DavisRayM committed Jul 17, 2020
1 parent 213c464 commit d8b677d
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
50 changes: 50 additions & 0 deletions onadata/apps/api/management/commands/elongate_odk_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from datetime import timedelta

from django.core.management.base import BaseCommand, CommandError
from django.utils.translation import gettext as _

from onadata.apps.api.models.odk_token import ODKToken


def elongate_odk_token(days: int, username: str):
qs = ODKToken.objects.filter(
user__username=username, status=ODKToken.ACTIVE)
if qs.count() < 1:
return False

token = qs.first()
updated_expiry_date = token.expires + timedelta(days=days)
token.expires = updated_expiry_date.astimezone(token.expires.tzinfo)
token.save()
return True


class Command(BaseCommand):
help = _("Elongate ODK Token for a particular user.")

def add_arguments(self, parser):
parser.add_argument(
'--days',
'-d',
default=30,
dest='days',
help='Number of days to elongate the token by.')
parser.add_argument(
'--username',
'-u',
dest='username',
help='The users username'
)

def handle(self, *args, **options):
username = options.get('username')
days = options.get('days')

if not username:
raise CommandError('No username provided.')

created = elongate_odk_token(days, username)
if not created:
raise CommandError(f'User {username} has no active ODK Token.')
self.stdout.write(
f'Elongated the active ODK Token for user {username}')
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from datetime import timedelta

from django.contrib.auth.models import User
from django.core.management import call_command
from django.utils.six import StringIO

from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.api.models.odk_token import ODKToken


class ElongateODKTokenTest(TestBase):
def test_elongate_odk_token(self):
user = User.objects.create(
username='dave', email='[email protected]')
token = ODKToken.objects.create(user=user)
expiry_date = token.expires

out = StringIO()
call_command(
'elongate_odk_token',
days=2,
username=user.username,
stdout=out
)

self.assertEqual(
'Elongated the active ODK Token for user dave\n',
out.getvalue())
token.refresh_from_db()
self.assertEqual(expiry_date + timedelta(days=2), token.expires)

0 comments on commit d8b677d

Please sign in to comment.