File size: 994 Bytes
32ddb29 9d66536 bf34e9d 32ddb29 9d66536 32ddb29 9d66536 32ddb29 bf34e9d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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"]) |