import os from datetime import datetime, timedelta, timezone from jose import jwt, JWTError from passlib.context import CryptContext from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from sqlalchemy.orm import Session from database import get_db from models import User SECRET_KEY = os.getenv("JWT_SECRET_KEY", "changeme") ALGORITHM = "HS256" TOKEN_HOURS = 72 pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") bearer = HTTPBearer() def hash_password(password: str) -> str: return pwd_context.hash(password) def verify_password(password: str, hashed: str) -> bool: return pwd_context.verify(password, hashed) def create_token(user_id: int, email: str) -> str: payload = { "sub": str(user_id), "email": email, "exp": datetime.now(timezone.utc) + timedelta(hours=TOKEN_HOURS), } return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM) def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(bearer), db: Session = Depends(get_db), ) -> User: token = credentials.credentials try: payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM]) user_id = int(payload.get("sub")) except (JWTError, ValueError): raise HTTPException(status.HTTP_401_UNAUTHORIZED, "Invalid or expired token") user = db.query(User).filter(User.id == user_id).first() if not user: raise HTTPException(status.HTTP_401_UNAUTHORIZED, "User not found") return user