import jwt import bcrypt from datetime import datetime, timedelta import os import dotenv dotenv.load_dotenv() AUTH_SECRET = os.getenv("AUTH_KEY") AUTH_TTL = int(os.getenv("AUTH_TTL")) def create_session(data: dict) -> str: """ Create a JWT token with expiration. """ expires_at = datetime.now() + timedelta(minutes=AUTH_TTL) token = jwt.encode({"exp": expires_at, **data}, AUTH_SECRET, algorithm="HS256") return token def check_session(token: str) -> dict: """ Verify the JWT token and return the decoded data. """ try: decoded = jwt.decode(token, AUTH_SECRET, algorithms=["HS256"]) return decoded except jwt.ExpiredSignatureError: raise ValueError("Token has expired") except jwt.InvalidTokenError: raise ValueError("Invalid token") def hide_pass(password: str) -> str: """ Hash the password using bcrypt. """ hashed = bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()) return hashed.decode("utf-8") def check_pass(password: str, hashed: str) -> bool: """ Compare the password with its hash. """ return bcrypt.checkpw(password.encode("utf-8"), hashed.encode("utf-8"))