Lab2: PostgreSQL, Bearer sessions and Redis for grade 4
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
import base64
|
||||
import binascii
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerifyMismatchError
|
||||
from argon2.low_level import Type
|
||||
|
||||
# Учебные параметры Argon2id: устойчивее SHA-256, но подъём на ноутбуке
|
||||
# остаётся коротким. В lab7 параметры будут заданы курсом отдельно.
|
||||
_TIME_COST = 2
|
||||
_MEMORY_COST = 32768
|
||||
_PARALLELISM = 1
|
||||
|
||||
_hasher: PasswordHasher | None = None
|
||||
_dummy_hash: str | None = None
|
||||
|
||||
|
||||
def get_hasher() -> PasswordHasher:
|
||||
global _hasher
|
||||
if _hasher is None:
|
||||
_hasher = PasswordHasher(
|
||||
time_cost=_TIME_COST,
|
||||
memory_cost=_MEMORY_COST,
|
||||
parallelism=_PARALLELISM,
|
||||
hash_len=32,
|
||||
salt_len=16,
|
||||
type=Type.ID,
|
||||
)
|
||||
return _hasher
|
||||
|
||||
|
||||
def init_security() -> None:
|
||||
global _dummy_hash
|
||||
if _dummy_hash is None:
|
||||
_dummy_hash = get_hasher().hash("messenger-dummy-password-not-used-for-login")
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return get_hasher().hash(password)
|
||||
|
||||
|
||||
def verify_password(password: str, password_hash: str | None) -> bool:
|
||||
init_security()
|
||||
try:
|
||||
get_hasher().verify(password_hash or _dummy_hash, password)
|
||||
matched = True
|
||||
except (VerifyMismatchError, InvalidHashError):
|
||||
matched = False
|
||||
return password_hash is not None and matched
|
||||
|
||||
|
||||
def parse_basic(header: str) -> tuple[str, str] | None:
|
||||
if not header:
|
||||
return None
|
||||
scheme, _, rest = header.partition(" ")
|
||||
if scheme.lower() != "basic" or not rest.strip():
|
||||
return None
|
||||
try:
|
||||
decoded = base64.b64decode(rest.strip(), validate=True)
|
||||
text = decoded.decode("utf-8")
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
return None
|
||||
username, separator, password = text.partition(":")
|
||||
if separator != ":" or len(username) > 256 or len(password) > 1024:
|
||||
return None
|
||||
return username, password
|
||||
Reference in New Issue
Block a user