feat(auth): add DB-backed login, token management, and idempotent auth migration
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
"""Password hashing and opaque token helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import secrets
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
salt = secrets.token_bytes(16)
|
||||
derived = hashlib.scrypt(password.encode("utf-8"), salt=salt, n=16384, r=8, p=1)
|
||||
return "scrypt$16384$8$1${}${}".format(
|
||||
base64.b64encode(salt).decode("ascii"),
|
||||
base64.b64encode(derived).decode("ascii"),
|
||||
)
|
||||
|
||||
|
||||
def verify_password(password: str, encoded: str | None) -> bool:
|
||||
if not encoded:
|
||||
return False
|
||||
try:
|
||||
algorithm, n_value, r_value, p_value, salt_encoded, digest_encoded = encoded.split("$", maxsplit=5)
|
||||
except ValueError:
|
||||
return False
|
||||
if algorithm != "scrypt":
|
||||
return False
|
||||
salt = base64.b64decode(salt_encoded.encode("ascii"))
|
||||
expected = base64.b64decode(digest_encoded.encode("ascii"))
|
||||
actual = hashlib.scrypt(
|
||||
password.encode("utf-8"),
|
||||
salt=salt,
|
||||
n=int(n_value),
|
||||
r=int(r_value),
|
||||
p=int(p_value),
|
||||
)
|
||||
return hmac.compare_digest(actual, expected)
|
||||
|
||||
|
||||
def generate_token() -> str:
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
def hash_token(token: str) -> str:
|
||||
return hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
|
||||
|
||||
def token_prefix(token: str) -> str:
|
||||
return token[:8]
|
||||
Reference in New Issue
Block a user