ЛР 2: PostgreSQL, сессии и Valkey — на 4
This commit is contained in:
@@ -0,0 +1,47 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError, InvalidHashError
|
||||
|
||||
from src.errors import ApiError
|
||||
|
||||
# Explicit bounded Argon2id parameters: 19 MiB, 2 passes, one lane.
|
||||
hasher = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||
DUMMY_HASH = hasher.hash(secrets.token_urlsafe(32))
|
||||
|
||||
|
||||
def unauthorized():
|
||||
raise ApiError(401, "unauthorized", "Требуется действительная сессия")
|
||||
|
||||
|
||||
def basic_credentials(header):
|
||||
try:
|
||||
scheme, value = header.split(" ", 1)
|
||||
if scheme.lower() != "basic":
|
||||
raise ValueError
|
||||
username, password = base64.b64decode(value, validate=True).decode("utf-8").split(":", 1)
|
||||
if not re.fullmatch(r"[a-z0-9_]{3,32}", username) or not 12 <= len(password) <= 128:
|
||||
raise ValueError
|
||||
return username, password
|
||||
except (ValueError, UnicodeError, AttributeError):
|
||||
unauthorized()
|
||||
|
||||
|
||||
def verify(encoded, password):
|
||||
try:
|
||||
return hasher.verify(encoded or DUMMY_HASH, password)
|
||||
except (VerificationError, InvalidHashError):
|
||||
return False
|
||||
|
||||
|
||||
def token_hash(header):
|
||||
try:
|
||||
scheme, token = header.split(" ", 1)
|
||||
if scheme.lower() != "bearer" or not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
|
||||
raise ValueError
|
||||
return hashlib.sha256(token.encode("ascii")).digest()
|
||||
except (ValueError, AttributeError):
|
||||
unauthorized()
|
||||
Reference in New Issue
Block a user