44 lines
1.2 KiB
Python
44 lines
1.2 KiB
Python
"""密码哈希(bcrypt)与 JWT 签发/校验。"""
|
|
from datetime import datetime, timedelta, timezone
|
|
|
|
import bcrypt
|
|
import jwt
|
|
|
|
from app.config import settings
|
|
|
|
_BCRYPT_ROUNDS = 12
|
|
|
|
|
|
def hash_password(password: str) -> str:
|
|
hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt(rounds=_BCRYPT_ROUNDS))
|
|
return hashed.decode("utf-8")
|
|
|
|
|
|
def verify_password(password: str, password_hash: str) -> bool:
|
|
try:
|
|
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
|
|
except ValueError:
|
|
return False
|
|
|
|
|
|
def create_access_token(subject: str) -> str:
|
|
"""subject 为 user id。"""
|
|
now = datetime.now(timezone.utc)
|
|
payload = {
|
|
"sub": subject,
|
|
"iat": now,
|
|
"exp": now + timedelta(minutes=settings.access_token_expire_minutes),
|
|
}
|
|
return jwt.encode(payload, settings.jwt_secret, algorithm=settings.jwt_algorithm)
|
|
|
|
|
|
def decode_access_token(token: str) -> str | None:
|
|
"""返回 user id,失败返回 None。"""
|
|
try:
|
|
payload = jwt.decode(
|
|
token, settings.jwt_secret, algorithms=[settings.jwt_algorithm]
|
|
)
|
|
return payload.get("sub")
|
|
except jwt.PyJWTError:
|
|
return None
|