"""Single-use password links with per-purpose lifetimes (specification 3).""" from typing import Any from django.conf import settings from django.contrib.auth.tokens import PasswordResetTokenGenerator from django.utils.crypto import constant_time_compare from django.utils.http import base36_to_int from apps.users.application.dto import PasswordLinkPurpose class PasswordLinkTokenGenerator(PasswordResetTokenGenerator): """Token that stops working when the password is set or a newer link is issued. The hash covers the password hash (changes when the password is set: single use) and ``password_link_nonce`` (incremented for every new link: older links die). """ def __init__(self, purpose: PasswordLinkPurpose, timeout_seconds: int) -> None: super().__init__() self.purpose = purpose self.timeout_seconds = timeout_seconds self.key_salt = f"apps.users.password_link.{purpose.value}" def _make_hash_value(self, user: Any, timestamp: int) -> str: return f"{user.pk}{user.password}{user.password_link_nonce}{timestamp}{user.email}" def check_token(self, user: Any, token: str | None) -> bool: if not (user and token): return False try: ts_b36, _ = token.split("-") ts = base36_to_int(ts_b36) except ValueError: return False for secret in [self.secret, *self.secret_fallbacks]: if constant_time_compare(self._make_token_with_timestamp(user, ts, secret), token): break else: return False return (self._num_seconds(self._now()) - ts) <= self.timeout_seconds def token_generator(purpose: PasswordLinkPurpose) -> PasswordLinkTokenGenerator: timeout = ( settings.PASSWORD_LINK_SETUP_TIMEOUT if purpose is PasswordLinkPurpose.SETUP else settings.PASSWORD_RESET_TIMEOUT ) return PasswordLinkTokenGenerator(purpose, timeout)