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-05-15 20:15:01 +00:00
|
|
|
from passbook.core.models import Token, User
|
2019-10-10 12:05:16 +00:00
|
|
|
from passbook.lib.config import CONFIG
|
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
|
|
|
class Command(BaseCommand):
|
2020-05-15 20:15:01 +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-15 20:15:01 +00:00
|
|
|
def get_url(self, token: Token) -> str:
|
2019-10-10 12:05:16 +00:00
|
|
|
"""Get full recovery link"""
|
2020-05-15 20:15:01 +00:00
|
|
|
path = reverse("passbook_recovery:use-token", kwargs={"uuid": str(token.uuid)})
|
2019-10-10 12:05:16 +00:00
|
|
|
return f"https://{CONFIG.y('domain')}{path}"
|
|
|
|
|
|
|
|
def handle(self, *args, **options):
|
2020-05-15 20:15:01 +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
|
|
|
delta = timedelta(days=duration * 365.2425)
|
|
|
|
_now = now()
|
|
|
|
expiry = _now + delta
|
2019-12-31 11:51:16 +00:00
|
|
|
user = User.objects.get(username=options.get("user"))
|
2020-05-15 20:15:01 +00:00
|
|
|
token = Token.objects.create(
|
2019-10-10 12:05:16 +00:00
|
|
|
expires=expiry,
|
|
|
|
user=user,
|
2020-05-15 20:15:01 +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-15 20:15:01 +00:00
|
|
|
self.stdout.write(self.get_url(token))
|