forked from mtusi2026/mtusi2026lab6
57 lines
1.5 KiB
Python
57 lines
1.5 KiB
Python
"""Хеширование паролей (Argon2id) и выпуск непрозрачных токенов сессий."""
|
|
|
|
import asyncio
|
|
import hashlib
|
|
import os
|
|
import secrets
|
|
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
from argon2 import PasswordHasher
|
|
from argon2.exceptions import InvalidHashError, VerificationError
|
|
|
|
TOKEN_BYTES = 32
|
|
|
|
_hasher = PasswordHasher()
|
|
_executor = ThreadPoolExecutor(
|
|
max_workers=max(1, min(2, (os.cpu_count() or 1) // _hasher.parallelism)),
|
|
thread_name_prefix="argon2",
|
|
)
|
|
|
|
|
|
def _hash_password_sync(password: str) -> str:
|
|
return _hasher.hash(password)
|
|
|
|
|
|
def _verify_password_sync(password: str, password_hash: str) -> bool:
|
|
try:
|
|
return _hasher.verify(password_hash, password)
|
|
except (VerificationError, InvalidHashError):
|
|
return False
|
|
|
|
|
|
_DUMMY_HASH = _hash_password_sync(secrets.token_urlsafe(TOKEN_BYTES))
|
|
|
|
|
|
async def hash_password(password: str) -> str:
|
|
loop = asyncio.get_running_loop()
|
|
return await loop.run_in_executor(_executor, _hash_password_sync, password)
|
|
|
|
|
|
async def verify_password(password: str, password_hash: str) -> bool:
|
|
loop = asyncio.get_running_loop()
|
|
return await loop.run_in_executor(
|
|
_executor, _verify_password_sync, password, password_hash
|
|
)
|
|
|
|
|
|
async def dummy_verify_password(password: str) -> None:
|
|
await verify_password(password, _DUMMY_HASH)
|
|
|
|
|
|
def generate_token() -> str:
|
|
return secrets.token_urlsafe(TOKEN_BYTES)
|
|
|
|
|
|
def hash_token(token: str) -> str:
|
|
return hashlib.sha256(token.encode()).hexdigest()
|