Files
DecomEval/backend/app/security.py

73 lines
2.1 KiB
Python

from __future__ import annotations
import base64
import hashlib
import hmac
import json
import os
import time
from typing import Any
from app.config import installed
ITERATIONS = 200_000
TOKEN_TTL = 12 * 60 * 60
def hash_password(password: str) -> str:
salt = os.urandom(16)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, ITERATIONS)
return f"{salt.hex()}${digest.hex()}"
def verify_password(password: str, stored: str) -> bool:
salt_hex, digest_hex = stored.split("$", 1)
digest = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), ITERATIONS)
return hmac.compare_digest(digest.hex(), digest_hex)
def _encode(data: dict[str, Any]) -> str:
raw = json.dumps(data, separators=(",", ":")).encode("utf-8")
return base64.urlsafe_b64encode(raw).decode("ascii").rstrip("=")
def _decode(raw: str) -> dict[str, Any]:
padded = raw + "=" * (-len(raw) % 4)
return json.loads(base64.urlsafe_b64decode(padded.encode("ascii")))
def jwt_secret() -> str:
if not installed():
raise RuntimeError("尚未安装")
from app.db import session_scope
from app.models import AppSetting
with session_scope() as session:
setting = session.get(AppSetting, 1)
if setting is None or not setting.jwt_secret:
raise RuntimeError("尚未安装")
return setting.jwt_secret
def issue_token(payload: dict[str, Any]) -> str:
body = {**payload, "exp": int(time.time()) + TOKEN_TTL}
raw = _encode(body)
signature = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest()
return f"{raw}.{signature}"
def read_token(token: str) -> dict[str, Any] | None:
raw, _, signature = token.partition(".")
if not raw or not signature:
return None
expected = hmac.new(jwt_secret().encode("utf-8"), raw.encode("ascii"), hashlib.sha256).hexdigest()
if not hmac.compare_digest(expected, signature):
return None
try:
body = _decode(raw)
except (ValueError, json.JSONDecodeError):
return None
if int(body.get("exp") or 0) < int(time.time()):
return None
return body