emcp/backend/app/core/security.py

28 lines
759 B
Python
Raw Normal View History

2026-05-18 09:12:14 +08:00
import hashlib
import secrets
from typing import Optional
from fastapi import Header, HTTPException, status
from app.core.config import settings
def hash_password(password: str) -> str:
return hashlib.sha256(password.encode("utf-8")).hexdigest()
def verify_password(password: str, expected_hash: str) -> bool:
return hash_password(password) == expected_hash
def verify_access_password(password: str) -> bool:
return secrets.compare_digest(password, settings.auth_password)
def verify_api_token(x_api_token: Optional[str] = Header(default=None)) -> None:
if x_api_token != settings.auth_password:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="无效的访问令牌",
)