api / app /utils /auth.py
hanbinsite's picture
feat: complete core feature improvements
bf34e9d
Raw History Blame Contribute Delete
994 Bytes
from datetime import datetime, timedelta, timezone
import bcrypt
import jwt
from app.config import settings
def hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def verify_password(plain_password: str, hashed_password: str) -> bool:
return bcrypt.checkpw(plain_password.encode("utf-8"), hashed_password.encode("utf-8"))
def create_access_token(subject: str, token_type: str = "admin", expires_delta: timedelta | None = None) -> str:
if expires_delta is None:
expires_delta = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
expire = datetime.now(timezone.utc) + expires_delta
to_encode = {"sub": subject, "type": token_type, "exp": expire}
return jwt.encode(to_encode, settings.SECRET_KEY, algorithm="HS256")
def decode_access_token(token: str) -> dict:
"""解码 JWT,失败抛出 jwt.PyJWTError"""
return jwt.decode(token, settings.SECRET_KEY, algorithms=["HS256"])