from datetime import datetime, timedelta import bcrypt from jose import jwt, JWTError from app.config import settings def get_password_hash(password: str) -> str: pwd_bytes = password.encode("utf-8")[:72] salt = bcrypt.gensalt() hashed = bcrypt.hashpw(pwd_bytes, salt) return hashed.decode("utf-8") def verify_password(plain_password: str, hashed_password: str) -> bool: pwd_bytes = plain_password.encode("utf-8")[:72] hashed_bytes = hashed_password.encode("utf-8") return bcrypt.checkpw(pwd_bytes, hashed_bytes) def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str: to_encode = data.copy() if expires_delta: expire = datetime.utcnow() + expires_delta else: expire = datetime.utcnow() + timedelta(minutes=settings.access_token_expire_minutes) to_encode.update({"exp": expire}) encoded_jwt = jwt.encode(to_encode, settings.secret_key, algorithm=settings.algorithm) return encoded_jwt def decode_token(token: str) -> dict | None: try: payload = jwt.decode(token, settings.secret_key, algorithms=[settings.algorithm]) return payload except JWTError as e: print(f"JWT decode error: {e}") return None