55 lines
1.7 KiB
Python
55 lines
1.7 KiB
Python
"""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
|
|
|
|
from passbook.core.models import Token, TokenIntents, User
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
class Command(BaseCommand):
|
|
"""Create Token used to recover access"""
|
|
|
|
help = _("Create a Key which can be used to restore access to passbook.")
|
|
|
|
def add_arguments(self, parser):
|
|
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."
|
|
)
|
|
|
|
def get_url(self, token: Token) -> str:
|
|
"""Get full recovery link"""
|
|
return reverse("passbook_recovery:use-token", kwargs={"key": str(token.key)})
|
|
|
|
def handle(self, *args, **options):
|
|
"""Create Token used to recover access"""
|
|
duration = int(options.get("duration", 1))
|
|
_now = now()
|
|
expiry = _now + timedelta(days=duration * 365.2425)
|
|
user = User.objects.get(username=options.get("user"))
|
|
token = Token.objects.create(
|
|
expires=expiry,
|
|
user=user,
|
|
intent=TokenIntents.INTENT_RECOVERY,
|
|
description=f"Recovery Token generated by {getuser()} on {_now}",
|
|
)
|
|
self.stdout.write(
|
|
(
|
|
f"Store this link safely, as it will allow"
|
|
f" anyone to access passbook as {user}."
|
|
)
|
|
)
|
|
self.stdout.write(self.get_url(token))
|