forked from mtusi2026/mtusi2026lab4
4
This commit is contained in:
@@ -0,0 +1,72 @@
|
||||
"""Пароли (Argon2id), токены, разбор заголовка Authorization."""
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
|
||||
from argon2 import PasswordHasher, Type
|
||||
from argon2.exceptions import InvalidHashError, VerificationError
|
||||
|
||||
from . import config
|
||||
|
||||
_hasher = PasswordHasher(time_cost=config.ARGON2_TIME_COST, memory_cost=config.ARGON2_MEMORY_KIB,
|
||||
parallelism=1, hash_len=32, salt_len=16, type=Type.ID)
|
||||
_DUMMY_HASH = _hasher.hash("dummy-password-for-constant-time")
|
||||
_hash_slots = threading.BoundedSemaphore(config.HASH_CONCURRENCY)
|
||||
_TOKEN_RE = re.compile(r"[A-Za-z0-9._~+/=-]{16,512}")
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
with _hash_slots:
|
||||
return _hasher.hash(password)
|
||||
|
||||
|
||||
def verify_password(stored_hash, password):
|
||||
with _hash_slots:
|
||||
try:
|
||||
_hasher.verify(stored_hash, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False, None
|
||||
return True, (_hasher.hash(password) if _hasher.check_needs_rehash(stored_hash) else None)
|
||||
|
||||
|
||||
def burn_verify(password):
|
||||
with _hash_slots:
|
||||
try:
|
||||
_hasher.verify(_DUMMY_HASH, password)
|
||||
except VerificationError:
|
||||
pass
|
||||
|
||||
|
||||
def new_token():
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
|
||||
|
||||
def parse_basic(header):
|
||||
if not header:
|
||||
return None
|
||||
scheme, _, rest = header.partition(" ")
|
||||
if scheme.lower() != "basic":
|
||||
return None
|
||||
try:
|
||||
text = base64.b64decode(rest.strip(), validate=True).decode("utf-8")
|
||||
except (binascii.Error, UnicodeDecodeError, ValueError):
|
||||
return None
|
||||
username, sep, password = text.partition(":")
|
||||
return (username, password) if sep else None
|
||||
|
||||
|
||||
def parse_bearer(header):
|
||||
if not header:
|
||||
return None
|
||||
scheme, _, rest = header.partition(" ")
|
||||
token = rest.strip()
|
||||
if scheme.lower() != "bearer" or not _TOKEN_RE.fullmatch(token):
|
||||
return None
|
||||
return token
|
||||
Reference in New Issue
Block a user