import threading from argon2 import PasswordHasher from argon2.exceptions import InvalidHashError, VerificationError from argon2.low_level import Type from src.errors import DomainError class Passwords: def __init__(self): self.hasher = PasswordHasher( time_cost=3, memory_cost=65536, parallelism=4, type=Type.ID ) self.slots = threading.BoundedSemaphore(2) self.dummy = self.hasher.hash("Synthetic-dummy-password-not-for-login") def _run(self, function, *args): if not self.slots.acquire(timeout=5): raise DomainError(503, "unavailable", "Authentication busy") try: return function(*args) finally: self.slots.release() def hash(self, *, password: str) -> str: return self._run(self.hasher.hash, password) def verify(self, *, password: str, encoded: str | None) -> bool: try: return ( self._run(self.hasher.verify, encoded or self.dummy, password) and encoded is not None ) except VerificationError, InvalidHashError: return False