2022-11-16 17:12:38 +00:00
|
|
|
"""
|
|
|
|
New device key used to obtain access token.
|
|
|
|
"""
|
2023-01-11 17:02:01 +00:00
|
|
|
from datetime import datetime, timedelta, timezone
|
2022-11-16 17:12:38 +00:00
|
|
|
import secrets
|
|
|
|
from pydantic import BaseModel
|
|
|
|
from mnemonic import Mnemonic
|
|
|
|
|
2023-01-11 17:02:01 +00:00
|
|
|
from selfprivacy_api.models.tokens.time import is_past
|
|
|
|
|
2022-11-16 17:12:38 +00:00
|
|
|
|
|
|
|
class NewDeviceKey(BaseModel):
|
|
|
|
"""
|
|
|
|
Recovery key used to obtain access token.
|
|
|
|
|
|
|
|
Recovery key has a key string, date of creation, date of expiration.
|
|
|
|
"""
|
|
|
|
|
|
|
|
key: str
|
|
|
|
created_at: datetime
|
|
|
|
expires_at: datetime
|
|
|
|
|
|
|
|
def is_valid(self) -> bool:
|
|
|
|
"""
|
|
|
|
Check if the recovery key is valid.
|
|
|
|
"""
|
2023-01-11 17:02:01 +00:00
|
|
|
if is_past(self.expires_at):
|
2022-11-16 17:12:38 +00:00
|
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
|
|
def as_mnemonic(self) -> str:
|
|
|
|
"""
|
|
|
|
Get the recovery key as a mnemonic.
|
|
|
|
"""
|
|
|
|
return Mnemonic(language="english").to_mnemonic(bytes.fromhex(self.key))
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def generate() -> "NewDeviceKey":
|
|
|
|
"""
|
|
|
|
Factory to generate a random token.
|
|
|
|
"""
|
2023-01-11 17:02:01 +00:00
|
|
|
creation_date = datetime.now(timezone.utc)
|
2022-11-16 17:12:38 +00:00
|
|
|
key = secrets.token_bytes(16).hex()
|
|
|
|
return NewDeviceKey(
|
|
|
|
key=key,
|
|
|
|
created_at=creation_date,
|
2023-01-11 17:02:01 +00:00
|
|
|
expires_at=creation_date + timedelta(minutes=10),
|
2022-11-16 17:12:38 +00:00
|
|
|
)
|