mirror of
https://git.victorphan.net/basketballcantho/ten-project.git
synced 2026-08-05 11:23:10 +07:00
hoàn thành phần Authentication
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import os
|
||||
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
# ── 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 ──────────────────────────────────────────────────────────
|
||||
_pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
|
||||
def hash_password(plain: str) -> str:
|
||||
return _pwd_context.hash(plain)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return _pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
# ── 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)
|
||||
Reference in New Issue
Block a user