Spaces:
Running

File size: 11,631 Bytes
e81d9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b944d36
 
e81d9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cd68f8
 
e81d9dd
 
 
 
2cd68f8
e81d9dd
 
 
 
 
 
 
 
 
 
2cd68f8
 
 
 
 
 
 
 
 
 
 
 
 
 
e81d9dd
2cd68f8
e81d9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cd68f8
e81d9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6729b8b
 
e81d9dd
 
6729b8b
 
e81d9dd
6729b8b
e81d9dd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
"""
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)}"
        )