unis-oa/backend/app/security.py

85 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Password hashing and JWT helpers."""
from __future__ import annotations
import hashlib
import secrets
from datetime import datetime, timedelta, timezone
from typing import Any
import bcrypt
from jose import JWTError, jwt
from .config import settings
# bcrypt reads at most 72 bytes of the password.
_MAX_PASSWORD_BYTES = 72
def _encode(raw: str) -> bytes:
return raw.encode("utf-8")[:_MAX_PASSWORD_BYTES]
def hash_password(raw: str) -> str:
return bcrypt.hashpw(_encode(raw), bcrypt.gensalt(rounds=10)).decode("utf-8")
def verify_password(raw: str, hashed: str) -> bool:
if not hashed:
return False
try:
return bcrypt.checkpw(_encode(raw), hashed.encode("utf-8"))
except ValueError:
return False
def session_idle_minutes() -> int:
"""空闲多久要求重新登录(分钟);0 或负数表示不启用。"""
try:
return max(0, int(settings.session_idle_minutes or 0))
except (TypeError, ValueError):
return 0
def create_access_token(subject: str, extra: dict[str, Any] | None = None) -> tuple[str, int]:
expires_in = settings.access_token_minutes * 60
# 开了空闲超时的话,访问令牌本身就不能活得比空闲窗口还久:访问令牌是自包含 JWT,
# 在这期间内后端拦不住它,只靠刷新时检查等于没做(对接指南第 8 节)。
idle = session_idle_minutes()
if idle:
expires_in = min(expires_in, idle * 60)
now = datetime.now(timezone.utc)
payload: dict[str, Any] = {
"sub": subject,
"iat": int(now.timestamp()),
"exp": int((now + timedelta(seconds=expires_in)).timestamp()),
"type": "access",
}
if extra:
payload.update(extra)
token = jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
return token, expires_in
def create_refresh_token(subject: str) -> tuple[str, datetime]:
expires_at = datetime.now(timezone.utc) + timedelta(days=settings.refresh_token_days)
payload = {
"sub": subject,
"jti": secrets.token_hex(16),
"exp": int(expires_at.timestamp()),
"type": "refresh",
}
token = jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
return token, expires_at.replace(tzinfo=None)
def decode_token(token: str) -> dict[str, Any]:
payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.jwt_algorithm])
if payload.get("type") not in {"access", "refresh"}:
raise JWTError("unexpected token type")
return payload
def hash_token(token: str) -> str:
return hashlib.sha256(token.encode("utf-8")).hexdigest()