from datetime import datetime, timedelta from typing import Optional from passlib.context import CryptContext from jose import JWTError, jwt from fastapi import Depends, HTTPException, status from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials from app.config import settings from app.models import User from sqlalchemy.orm import Session from app.database.database import get_db pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto") security = HTTPBearer() def verify_password(plain_password: str, hashed_password: str) -> bool: return pwd_context.verify(plain_password, hashed_password) def get_password_hash(password: str) -> str: return pwd_context.hash(password) def create_access_token(data: dict, expires_delta: Optional[timedelta] = 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.jwt_secret_key, algorithm=settings.jwt_algorithm ) return encoded_jwt def verify_token(token: str) -> Optional[int]: try: payload = jwt.decode( token, settings.jwt_secret_key, algorithms=[settings.jwt_algorithm] ) user_id_str: str = payload.get("sub") if user_id_str is None: return None # Convert string to integer user_id = int(user_id_str) return user_id except JWTError as e: return None except (ValueError, TypeError) as e: return None except Exception as e: return None def authenticate_user(db: Session, email: str, password: str) -> Optional[User]: user = db.query(User).filter(User.email == email).first() if not user or not verify_password(password, user.hashed_password): return None return user def get_current_user( credentials: HTTPAuthorizationCredentials = Depends(security), db: Session = Depends(get_db), ) -> User: token = credentials.credentials user_id = verify_token(token) if user_id is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authentication credentials", ) user = db.query(User).filter(User.id == user_id).first() if user is None: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found", ) return user def get_current_admin_user(current_user: User = Depends(get_current_user)) -> User: if not current_user.is_admin: raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required", ) return current_user