Skip to content

Commit

Permalink
Add "increase_odk_token_lifetime" management command
Browse files Browse the repository at this point in the history
  • Loading branch information
DavisRayM committed Jul 17, 2020
1 parent c6d9a0c commit 6cf5edc
Show file tree
Hide file tree
Showing 2 changed files with 80 additions and 0 deletions.
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 increase_odk_token_lifetime(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 = _("Increase ODK Token lifetime for a particular user.")

def add_arguments(self, parser):
parser.add_argument(
'--days',
'-d',
default=30,
dest='days',
help='Number of days to increase the token lifetime 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 = increase_odk_token_lifetime(days, username)
if not created:
raise CommandError(f'User {username} has no active ODK Token.')
self.stdout.write(
f'Increased the lifetime of 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 IncreaseODKTokenLifetimeTest(TestBase):
def test_increase_odk_token_lifetime(self):
user = User.objects.create(
username='dave', email='[email protected]')
token = ODKToken.objects.create(user=user)
expiry_date = token.expires

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

self.assertEqual(
'Increased the lifetime of 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 6cf5edc

Please sign in to comment.