Spaces:
Paused
Paused
| """ | |
| Authentication Routes - Google OAuth | |
| """ | |
| from fastapi import APIRouter, Request, HTTPException, Depends | |
| from fastapi.responses import RedirectResponse, JSONResponse | |
| from pydantic import BaseModel | |
| from typing import Optional | |
| import secrets | |
| from app.auth.google_oauth import get_google_oauth | |
| from app.core.api_gateway import AccountManager, Account | |
| router = APIRouter(prefix="/auth", tags=["auth"]) | |
| async def google_login(): | |
| """Redirect to Google OAuth login.""" | |
| oauth = get_google_oauth() | |
| auth_url = oauth.get_auth_url() | |
| return RedirectResponse(auth_url) | |
| async def google_callback(request: Request, code: str, state: str): | |
| """Handle Google OAuth callback.""" | |
| oauth = get_google_oauth() | |
| # Verify state | |
| if not oauth.verify_state(state): | |
| raise HTTPException(status_code=400, detail="Invalid state parameter") | |
| try: | |
| # Exchange code for token | |
| token_data = await oauth.exchange_code_for_token(code) | |
| access_token = token_data.get("access_token") | |
| # Get user info | |
| user_info = await oauth.get_user_info(access_token) | |
| email = user_info.get("email") | |
| name = user_info.get("name") | |
| google_id = user_info.get("id") | |
| # Find or create account | |
| account = AccountManager.get_account_by_email(email) | |
| if not account: | |
| # Create new account | |
| account = AccountManager.create_account( | |
| email=email, | |
| password=secrets.token_urlsafe(32), # Random password for OAuth users | |
| name=name | |
| ) | |
| # Create default API key | |
| account.add_api_key("Default Key") | |
| # Create session token | |
| session_token = secrets.token_urlsafe(32) | |
| # Redirect to dashboard with session token | |
| return RedirectResponse( | |
| f"/m5?token={session_token}&email={email}", | |
| status_code=302 | |
| ) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"OAuth error: {str(e)}") | |
| async def logout(): | |
| """Logout and redirect to home.""" | |
| response = RedirectResponse("/") | |
| response.delete_cookie("session_token") | |
| return response | |
| async def get_current_user(request: Request): | |
| """Get current authenticated user.""" | |
| # In production, verify session token from cookie/header | |
| # For now, return mock data | |
| return { | |
| "authenticated": False, | |
| "message": "Implement session verification" | |
| } | |