mirror of
https://git.victorphan.net/basketballcantho/ten-project.git
synced 2026-08-05 15:13:11 +07:00
42 lines
1.6 KiB
Python
42 lines
1.6 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
import os
|
|
|
|
import bcrypt
|
|
from jose import JWTError, jwt
|
|
|
|
# ── Config (override via environment variables) ───────────────────────────────
|
|
SECRET_KEY: str = os.environ["JWT_SECRET_KEY"] # must be set — no default
|
|
ALGORITHM: str = os.getenv("JWT_ALGORITHM", "HS256")
|
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = int(
|
|
os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "60")
|
|
)
|
|
|
|
# ── Password hashing (use bcrypt directly — passlib has compat issues) ────────
|
|
|
|
def hash_password(plain: str) -> str:
|
|
return bcrypt.hashpw(plain.encode(), bcrypt.gensalt()).decode()
|
|
|
|
|
|
def verify_password(plain: str, hashed: str) -> bool:
|
|
return bcrypt.checkpw(plain.encode(), hashed.encode())
|
|
|
|
|
|
# ── JWT ───────────────────────────────────────────────────────────────────────
|
|
|
|
def create_access_token(user_id: int) -> str:
|
|
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
payload = {"sub": str(user_id), "exp": expire}
|
|
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
|
|
|
|
|
def decode_access_token(token: str) -> int:
|
|
"""
|
|
Decode the JWT and return the user_id (int).
|
|
Raises JWTError on any validation failure.
|
|
"""
|
|
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
|
sub = payload.get("sub")
|
|
if sub is None:
|
|
raise JWTError("Missing subject claim.")
|
|
return int(sub)
|