from fastapi import HTTPException, status, Depends, Header from sqlalchemy.orm import Session from typing import Optional from app.db.session import get_db from app.models.user import User from app.services.google_oauth_service import GoogleOAuthService async def get_current_user( authorization: Optional[str] = Header(None), db: Session = Depends(get_db) ) -> User: if not authorization: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Authorization header required", headers={"WWW-Authenticate": "Bearer"}, ) # Extract token from "Bearer " format if not authorization.startswith("Bearer "): raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid authorization header format", headers={"WWW-Authenticate": "Bearer"}, ) google_token = authorization.split(" ")[1] # Verify Google token user_info = await GoogleOAuthService.verify_google_token(google_token) if not user_info: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid Google token", headers={"WWW-Authenticate": "Bearer"}, ) # Find user by email user = db.query(User).filter(User.email == user_info['email']).first() if not user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="User not found", headers={"WWW-Authenticate": "Bearer"}, ) # Ensure user is a Google user if not user.is_google_user: raise HTTPException( status_code=status.HTTP_401_UNAUTHORIZED, detail="Only Google authentication is supported", headers={"WWW-Authenticate": "Bearer"}, ) return user