2019-10-10 12:05:16 +00:00
|
|
|
"""passbook recovery createkey command"""
|
|
|
|
from datetime import timedelta
|
|
|
|
from getpass import getuser
|
|
|
|
|
|
|
|
from django.core.management.base import BaseCommand
|
|
|
|
from django.urls import reverse
|
|
|
|
from django.utils.timezone import now
|
|
|
|
from django.utils.translation import gettext as _
|
|
|
|
from structlog import get_logger
|
|
|
|
|
2020-10-03 21:37:58 +00:00
|
|
|
from passbook.core.models import Token, TokenIntents, User
|
2019-10-10 12:05:16 +00:00
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
2020-05-16 14:11:53 +00:00
|
|
|
"""Create Token used to recover access"""
|
2019-10-10 12:05:16 +00:00
|
|
|
|
2019-12-31 11:51:16 +00:00
|
|
|
help = _("Create a Key which can be used to restore access to passbook.")
|
2019-10-10 12:05:16 +00:00
|
|
|
|
|
|
|
def add_arguments(self, parser):
|
2019-12-31 11:51:16 +00:00
|
|
|
parser.add_argument(
|
|
|
|
"duration",
|
|
|
|
default=1,
|
|
|
|
action="store",
|
|
|
|
help="How long the token is valid for (in years).",
|
|
|
|
)
|
|
|
|
parser.add_argument(
|
|
|
|
"user", action="store", help="Which user the Token gives access to."
|
|
|
|
)
|
2019-10-10 12:05:16 +00:00
|
|
|
|
2020-05-16 14:11:53 +00:00
|
|
|
def get_url(self, token: Token) -> str:
|
2019-10-10 12:05:16 +00:00
|
|
|
"""Get full recovery link"""
|
2020-10-18 12:34:22 +00:00
|
|
|
return reverse("passbook_recovery:use-token", kwargs={"key": str(token.key)})
|
2019-10-10 12:05:16 +00:00
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
2020-05-16 14:11:53 +00:00
|
|
|
"""Create Token used to recover access"""
|
2019-12-31 11:51:16 +00:00
|
|
|
duration = int(options.get("duration", 1))
|
2019-10-10 12:05:16 +00:00
|
|
|
_now = now()
|
2020-10-18 12:34:22 +00:00
|
|
|
expiry = _now + timedelta(days=duration * 365.2425)
|
2019-12-31 11:51:16 +00:00
|
|
|
user = User.objects.get(username=options.get("user"))
|
2020-05-16 14:11:53 +00:00
|
|
|
token = Token.objects.create(
|
2019-10-10 12:05:16 +00:00
|
|
|
expires=expiry,
|
|
|
|
user=user,
|
2020-10-03 21:37:58 +00:00
|
|
|
intent=TokenIntents.INTENT_RECOVERY,
|
2020-05-16 14:11:53 +00:00
|
|
|
description=f"Recovery Token generated by {getuser()} on {_now}",
|
2019-12-31 11:51:16 +00:00
|
|
|
)
|
|
|
|
self.stdout.write(
|
|
|
|
(
|
|
|
|
f"Store this link safely, as it will allow"
|
|
|
|
f" anyone to access passbook as {user}."
|
|
|
|
)
|
|
|
|
)
|
2020-05-16 14:11:53 +00:00
|
|
|
self.stdout.write(self.get_url(token))
|