Spaces:
Running

axeronis
fix: use backend callback URL for OAuth redirect
b944d36
Raw History Blame Contribute Delete
11.6 kB
"""
OAuth Integration for Meta (Instagram & WhatsApp)
Simplifies connection process - users just click "Connect" button
"""
from fastapi import APIRouter, HTTPException, Depends, Query
from fastapi.responses import RedirectResponse
from sqlalchemy.ext.asyncio import AsyncSession
from pydantic import BaseModel
from typing import Optional
import httpx
from uuid import UUID
from app.core.database import get_async_session
from app.core.config import settings
from app.core.logging import get_logger
from app.api.deps import get_current_user
from app.models import User, Tenant
logger = get_logger(__name__)
router = APIRouter(prefix="/oauth", tags=["OAuth"])
# ==================== CONFIG ====================
# Meta App credentials (for centralized OAuth)
# TODO: Set these in environment variables
META_APP_ID = settings.META_APP_ID if hasattr(settings, 'META_APP_ID') else None
META_APP_SECRET = settings.META_APP_SECRET if hasattr(settings, 'META_APP_SECRET') else None
# Redirect to backend callback handler
META_REDIRECT_URI = "https://api.microfunnel.online/api/v1/oauth/meta/callback"
# ==================== SCHEMAS ====================
class OAuthInitResponse(BaseModel):
"""OAuth initialization response"""
authorization_url: str
state: str
# ==================== OAUTH FLOW ====================
@router.get("/meta/connect")
async def initiate_meta_oauth(
channel: str = Query(..., description="Channel: instagram or whatsapp"),
token: Optional[str] = Query(None, description="Bearer token for auth"),
session: AsyncSession = Depends(get_async_session)
):
"""
Step 1: Initiate OAuth flow for Instagram/WhatsApp
Accepts token via query param since this is accessed via browser redirect
"""
if not META_APP_ID:
raise HTTPException(
status_code=500,
detail="OAuth not configured. Please set META_APP_ID in environment"
)
if channel not in ["instagram", "whatsapp"]:
raise HTTPException(status_code=400, detail="Invalid channel")
# Verify token and get user
if not token:
raise HTTPException(status_code=401, detail="Token required")
from app.core.security import decode_access_token
try:
payload = decode_access_token(token)
user_id = payload.get("sub")
if not user_id:
raise HTTPException(status_code=401, detail="Invalid token")
except Exception as e:
logger.error(f"Token verification failed: {e}")
raise HTTPException(status_code=401, detail="Invalid token")
# Generate state to prevent CSRF (contains user_id and channel)
state = f"{user_id}:{channel}"
# Required permissions
if channel == "instagram":
scope = "instagram_basic,instagram_manage_messages,pages_messaging,pages_read_engagement"
else: # whatsapp
scope = "whatsapp_business_management,whatsapp_business_messaging"
# Meta OAuth URL
authorization_url = (
f"https://www.facebook.com/v18.0/dialog/oauth?"
f"client_id={META_APP_ID}&"
f"redirect_uri={META_REDIRECT_URI}&"
f"state={state}&"
f"scope={scope}&"
f"response_type=code"
)
logger.info(
"OAuth flow initiated",
user_id=user_id,
channel=channel
)
# Redirect user to Meta authorization page
return RedirectResponse(url=authorization_url)
@router.get("/meta/callback")
async def meta_oauth_callback(
code: str = Query(...),
state: str = Query(...),
session: AsyncSession = Depends(get_async_session)
):
"""
Step 2: OAuth callback from Meta
Exchanges authorization code for access token
Stores credentials and configures webhook
"""
if not META_APP_ID or not META_APP_SECRET:
raise HTTPException(
status_code=500,
detail="OAuth not configured"
)
try:
# Parse state (user_id:channel)
user_id_str, channel = state.split(":")
user_id = UUID(user_id_str)
# Get user and tenant
user = await session.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
tenant = await session.get(Tenant, user.tenant_id)
if not tenant:
raise HTTPException(status_code=404, detail="Tenant not found")
# Exchange code for access token
async with httpx.AsyncClient() as client:
token_response = await client.get(
"https://graph.facebook.com/v18.0/oauth/access_token",
params={
"client_id": META_APP_ID,
"client_secret": META_APP_SECRET,
"redirect_uri": META_REDIRECT_URI,
"code": code
},
timeout=10.0
)
if token_response.status_code != 200:
logger.error(
"Failed to exchange OAuth code",
status=token_response.status_code,
response=token_response.text
)
raise HTTPException(
status_code=400,
detail="Failed to obtain access token"
)
token_data = token_response.json()
access_token = token_data.get("access_token")
if not access_token:
raise HTTPException(
status_code=400,
detail="No access token in response"
)
# Get user's pages/accounts
if channel == "instagram":
# Get Instagram Business Accounts
accounts_response = await client.get(
"https://graph.facebook.com/v18.0/me/accounts",
params={"access_token": access_token},
timeout=10.0
)
if accounts_response.status_code != 200:
raise HTTPException(
status_code=400,
detail="Failed to get Instagram accounts"
)
accounts_data = accounts_response.json()
pages = accounts_data.get("data", [])
if not pages:
raise HTTPException(
status_code=400,
detail="No Instagram Business Account found"
)
# Use first page (could add UI to select)
page = pages[0]
page_id = page.get("id")
page_access_token = page.get("access_token")
# Get Instagram account ID
ig_response = await client.get(
f"https://graph.facebook.com/v18.0/{page_id}",
params={
"fields": "instagram_business_account",
"access_token": page_access_token
},
timeout=10.0
)
if ig_response.status_code != 200:
raise HTTPException(
status_code=400,
detail="Failed to get Instagram account"
)
ig_data = ig_response.json()
instagram_account = ig_data.get("instagram_business_account", {})
ig_user_id = instagram_account.get("id")
if not ig_user_id:
raise HTTPException(
status_code=400,
detail="No Instagram Business Account linked to this page"
)
# Save Instagram config
tenant.instagram_config = {
"access_token": page_access_token,
"page_id": ig_user_id,
"verify_token": "microfunnel-verify-token"
}
else: # whatsapp
# Get WhatsApp Business Accounts
waba_response = await client.get(
"https://graph.facebook.com/v18.0/me/businesses",
params={
"access_token": access_token,
"fields": "owned_whatsapp_business_accounts{phone_numbers}"
},
timeout=10.0
)
if waba_response.status_code != 200:
raise HTTPException(
status_code=400,
detail="Failed to get WhatsApp accounts"
)
waba_data = waba_response.json()
businesses = waba_data.get("data", [])
if not businesses or not businesses[0].get("owned_whatsapp_business_accounts"):
raise HTTPException(
status_code=400,
detail="No WhatsApp Business Account found"
)
waba = businesses[0]["owned_whatsapp_business_accounts"]["data"][0]
phone_numbers = waba.get("phone_numbers", {}).get("data", [])
if not phone_numbers:
raise HTTPException(
status_code=400,
detail="No phone number found in WhatsApp Business Account"
)
phone_number = phone_numbers[0]
phone_number_id = phone_number.get("id")
# Save WhatsApp config to meta_wa_config (for Cloud API)
tenant.meta_wa_config = {
"access_token": access_token,
"phone_number_id": phone_number_id,
"waba_id": waba.get("id"),
"verify_token": "microfunnel_webhook_2024"
}
tenant.whatsapp_connected = True
# Save to database
session.add(tenant)
await session.commit()
logger.info(
f"{channel.capitalize()} connected via OAuth",
tenant_id=str(tenant.id),
user_id=str(user.id)
)
# Redirect to success page
# Extract Vercel URL from Railway URL
if 'railway.app' in settings.TELEGRAM_WEBHOOK_URL:
# Railway: web-production-81733.up.railway.app
# Vercel: microfunnel-platform-*.vercel.app (get from env or hardcode)
frontend_url = settings.FRONTEND_URL or 'https://microfunnel-platform.vercel.app'
else:
frontend_url = settings.FRONTEND_URL or 'http://localhost:3000'
return RedirectResponse(
url=f"{frontend_url}/channels?success=true&channel={channel}"
)
except ValueError as e:
logger.error("Invalid state parameter", error=str(e))
raise HTTPException(status_code=400, detail="Invalid state parameter")
except Exception as e:
logger.error(
"OAuth callback error",
error=str(e),
exc_info=True
)
raise HTTPException(
status_code=500,
detail=f"OAuth failed: {str(e)}"
)