Files
mtusi2026lab7/app/auth/passwords.py
T

26 lines
815 B
Python

import os
from argon2 import PasswordHasher, Type
from argon2.exceptions import VerificationError, VerifyMismatchError
_memory = int(os.getenv('ARGON2_MEMORY_KIB', '19456'))
_iterations = int(os.getenv('ARGON2_ITERATIONS', '2'))
_parallelism = int(os.getenv('ARGON2_PARALLELISM', '1'))
if _memory < 19456 or _iterations < 2 or _parallelism < 1:
raise RuntimeError('Argon2id requires at least 19 MiB, t=2 and p=1')
_hasher = PasswordHasher(
memory_cost=_memory, time_cost=_iterations, parallelism=_parallelism, type=Type.ID,
)
def hash_password(password: str) -> str:
return _hasher.hash(password)
def password_matches(stored_hash: str, password: str) -> bool:
try:
return _hasher.verify(stored_hash, password)
except (VerifyMismatchError, VerificationError):
return False