Files
ai-agent-admin/backend/app/core/security.py
T
2026-06-08 15:05:57 +08:00

31 lines
1.0 KiB
Python

from datetime import datetime, timedelta, timezone
from typing import Any
import bcrypt
from jose import JWTError, jwt
from app.core.config import settings
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(password: str, password_hash: str) -> bool:
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
def create_access_token(subject: str, extra: dict[str, Any] | None = None) -> str:
expires = datetime.now(timezone.utc) + timedelta(minutes=settings.access_token_expire_minutes)
payload: dict[str, Any] = {"sub": subject, "exp": expires}
if extra:
payload.update(extra)
return jwt.encode(payload, settings.jwt_secret_key, algorithm=settings.jwt_algorithm)
def decode_access_token(token: str) -> dict[str, Any] | None:
try:
return jwt.decode(token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm])
except JWTError:
return None