forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_integrations.py
More file actions
905 lines (710 loc) · 34.3 KB
/
Copy pathtask_integrations.py
File metadata and controls
905 lines (710 loc) · 34.3 KB
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
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
from fastapi import APIRouter, Depends, HTTPException, Query, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from typing import Dict, Any, List, Optional
from pydantic import BaseModel, Field
from models.shared import StatusResponse
import os
import secrets
import json
from datetime import datetime, timedelta, timezone
import httpx
import database.users as users_db
import database.redis_db as redis_db
from utils.other import endpoints as auth
from utils.log_sanitizer import sanitize
from utils.executors import db_executor, run_blocking
from utils.task_integrations_ops import (
OAUTH_CONFIGS,
close_http_client,
create_task_internal,
ensure_valid_oauth_token,
get_http_client,
perform_request_with_token_retry,
)
import logging
logger = logging.getLogger(__name__)
router = APIRouter()
# OAuth state management
OAUTH_STATE_EXPIRY = 600 # 10 minutes
# Templates
templates = Jinja2Templates(directory="templates")
def render_oauth_response(
request: Request,
app_key: str,
success: bool = True,
redirect_url: Optional[str] = None,
error_type: Optional[str] = None,
) -> HTMLResponse:
"""
Render OAuth callback response using template.
Args:
request: FastAPI request object
app_key: Integration app key (todoist, asana, etc.)
success: Whether the OAuth flow was successful
redirect_url: Deep link URL to redirect to (for success case)
error_type: Type of error (missing_code, invalid_state, config_error, server_error)
"""
# Use a single, default gradient in the template (template now hardcodes it).
config = OAUTH_CONFIGS.get(app_key, {'name': app_key.title()})
if success:
context = {
'request': request,
'title': f"{config['name']} Auth",
'icon': '✓',
'message': 'Authentication Successful!',
'description': 'Redirecting back to Omi...',
'redirect_url': redirect_url or f'omi://{app_key}/callback?error=unknown',
'show_spinner': True,
}
else:
error_messages = {
'missing_code': 'No authorization code received from {}.'.format(config['name']),
'invalid_state': 'Invalid or expired authentication request.',
'config_error': '{} OAuth not properly configured.'.format(config['name']),
'server_error': 'An error occurred during authentication.',
}
context = {
'request': request,
'title': f"{config['name']} Auth Error",
'icon': '❌',
'message': f"{'Security' if error_type == 'invalid_state' else 'Configuration' if error_type == 'config_error' else 'Authentication'} Error",
'description': error_messages.get(error_type, 'An error occurred.'),
'redirect_url': f'omi://{app_key}/callback?error={error_type or "unknown"}',
'show_spinner': False,
}
return templates.TemplateResponse(request, 'oauth_callback.html', context)
def validate_and_consume_oauth_state(state_token: Optional[str]) -> Optional[Dict[str, str]]:
"""
Validate OAuth state token and return associated data.
Deletes the state token after validation to prevent replay attacks.
Returns:
Dict with 'uid' and 'app_key' if valid, None if invalid/expired
"""
if not state_token:
return None
state_key = f"oauth_state:{state_token}"
# Atomic get-and-delete: an OAuth state is single-use, so consuming it must be one operation.
# A separate GET then DELETE lets two concurrent callbacks carrying the same state both read the
# value before either delete runs, weakening replay protection. GETDEL removes it atomically, so
# only one caller ever receives the value.
state_data_str = redis_db.r.getdel(state_key)
if not state_data_str:
return None
try:
raw = state_data_str.decode() if isinstance(state_data_str, bytes) else state_data_str
try:
state_data = json.loads(raw)
except json.JSONDecodeError:
# Pre-migration writers stored str(dict) (single quotes). Those keys
# expire after OAUTH_STATE_EXPIRY (10 min). Map them to JSON without
# reintroducing ast.literal_eval.
state_data = json.loads(raw.replace("'", '"'))
if not isinstance(state_data, dict):
return None
return state_data
except Exception as e:
logger.error(f"Error parsing state data: {e}")
return None
# Request/Response models
class TaskIntegrationData(BaseModel):
"""Data for a task integration connection"""
# Common fields
connected: bool = True
access_token: Optional[str] = None
refresh_token: Optional[str] = None
# Asana-specific fields
user_gid: Optional[str] = None
workspace_gid: Optional[str] = None
workspace_name: Optional[str] = None
project_gid: Optional[str] = None
project_name: Optional[str] = None
# Google Tasks-specific fields
default_list_id: Optional[str] = None
default_list_title: Optional[str] = None
# ClickUp-specific fields
user_id: Optional[str] = None
team_id: Optional[str] = None
team_name: Optional[str] = None
space_id: Optional[str] = None
space_name: Optional[str] = None
list_id: Optional[str] = None
list_name: Optional[str] = None
class TaskIntegrationsResponse(BaseModel):
"""Response containing all task integrations"""
integrations: Dict[str, Any] = Field(description="Map of app_key to connection details")
default_app: Optional[str] = Field(description="Default task integration app key")
class DefaultTaskIntegrationRequest(BaseModel):
"""Request to set default task integration"""
app_key: str = Field(description="Task integration app key (e.g., 'asana', 'todoist')")
class DefaultTaskIntegrationResponse(BaseModel):
"""Response for default task integration"""
default_app: Optional[str] = Field(description="Default task integration app key")
class TaskIntegrationMutationResponse(BaseModel):
status: str
app_key: str
class AsanaWorkspacesResponse(BaseModel):
workspaces: List[Dict[str, Any]] = Field(default_factory=list)
class AsanaProjectsResponse(BaseModel):
projects: List[Dict[str, Any]] = Field(default_factory=list)
class ClickUpTeamsResponse(BaseModel):
teams: List[Dict[str, Any]] = Field(default_factory=list)
class ClickUpSpacesResponse(BaseModel):
spaces: List[Dict[str, Any]] = Field(default_factory=list)
class ClickUpListsResponse(BaseModel):
lists: List[Dict[str, Any]] = Field(default_factory=list)
# *****************************
# ********** ROUTES ***********
# *****************************
@router.get("/v1/task-integrations", response_model=TaskIntegrationsResponse, tags=['task-integrations'])
def get_task_integrations(uid: str = Depends(auth.get_current_user_uid)):
"""Get all task integration connections for the current user."""
integrations = users_db.get_task_integrations(uid)
default_app = users_db.get_default_task_integration(uid)
return TaskIntegrationsResponse(integrations=integrations, default_app=default_app)
@router.get("/v1/task-integrations/default", response_model=DefaultTaskIntegrationResponse, tags=['task-integrations'])
def get_default_task_integration(uid: str = Depends(auth.get_current_user_uid)):
"""Get the user's default task integration app."""
default_app = users_db.get_default_task_integration(uid)
return DefaultTaskIntegrationResponse(default_app=default_app)
@router.put("/v1/task-integrations/default", response_model=DefaultTaskIntegrationResponse, tags=['task-integrations'])
def set_default_task_integration(request: DefaultTaskIntegrationRequest, uid: str = Depends(auth.get_current_user_uid)):
"""Set the user's default task integration app."""
users_db.set_default_task_integration(uid, request.app_key)
return DefaultTaskIntegrationResponse(default_app=request.app_key)
@router.put(
"/v1/task-integrations/{app_key}", tags=['task-integrations'], response_model=TaskIntegrationMutationResponse
)
def save_task_integration(app_key: str, data: TaskIntegrationData, uid: str = Depends(auth.get_current_user_uid)):
"""Save or update a task integration connection."""
# Convert Pydantic model to dict, excluding None values
integration_data = data.model_dump(exclude_none=True)
users_db.set_task_integration(uid, app_key, integration_data)
return {"status": "ok", "app_key": app_key}
@router.delete("/v1/task-integrations/{app_key}", status_code=204, tags=['task-integrations'])
def delete_task_integration(app_key: str, uid: str = Depends(auth.get_current_user_uid)):
"""Delete a task integration connection."""
success = users_db.delete_task_integration(uid, app_key)
if not success:
raise HTTPException(status_code=404, detail="Task integration not found")
# If this was the default, clear it
default_app = users_db.get_default_task_integration(uid)
if default_app == app_key:
users_db.set_default_task_integration(uid, '')
# *****************************
# ****** OAuth Initiation *****
# *****************************
class OAuthUrlResponse(BaseModel):
"""Response containing OAuth authorization URL"""
auth_url: str = Field(description="OAuth authorization URL to open in browser")
@router.get("/v1/task-integrations/{app_key}/oauth-url", response_model=OAuthUrlResponse, tags=['task-integrations'])
def get_oauth_url(app_key: str, uid: str = Depends(auth.get_current_user_uid)):
"""
Get OAuth authorization URL for a task integration.
Frontend opens this URL in browser to start OAuth flow.
Uses secure random state tokens to prevent CSRF attacks.
"""
base_url = os.getenv('BASE_API_URL')
if not base_url:
raise HTTPException(status_code=500, detail="BASE_API_URL not configured")
# Normalize base_url: remove trailing slash to prevent redirect URI mismatches
base_url = base_url.rstrip('/')
# Generate cryptographically secure random state token
state_token = secrets.token_urlsafe(32)
# Store state mapping in Redis with expiry
state_key = f"oauth_state:{state_token}"
state_data = {'uid': uid, 'app_key': app_key, 'created_at': datetime.now(timezone.utc).isoformat()}
redis_db.r.setex(state_key, OAUTH_STATE_EXPIRY, json.dumps(state_data))
if app_key == 'todoist':
client_id = os.getenv('TODOIST_CLIENT_ID')
if not client_id:
raise HTTPException(status_code=500, detail="Todoist not configured")
base_url = base_url.rstrip('/')
redirect_uri = f'{base_url}/v2/integrations/todoist/callback'
auth_url = f'https://todoist.com/oauth/authorize?client_id={client_id}&scope=data:read_write&state={state_token}&redirect_uri={redirect_uri}'
elif app_key == 'asana':
client_id = os.getenv('ASANA_CLIENT_ID')
if not client_id:
raise HTTPException(status_code=500, detail="Asana not configured")
base_url = base_url.rstrip('/')
redirect_uri = f'{base_url}/v2/integrations/asana/callback'
scopes = 'tasks:read tasks:write workspaces:read projects:read users:read'
from urllib.parse import quote
auth_url = f'https://app.asana.com/-/oauth_authorize?client_id={client_id}&redirect_uri={quote(redirect_uri)}&response_type=code&state={state_token}&scope={quote(scopes)}'
elif app_key == 'google_tasks':
client_id = os.getenv('GOOGLE_TASKS_CLIENT_ID')
if not client_id:
raise HTTPException(status_code=500, detail="Google Tasks not configured")
base_url = base_url.rstrip('/')
redirect_uri = f'{base_url}/v2/integrations/google-tasks/callback'
scope = 'https://www.googleapis.com/auth/tasks'
from urllib.parse import quote
auth_url = f'https://accounts.google.com/o/oauth2/v2/auth?client_id={client_id}&redirect_uri={quote(redirect_uri)}&response_type=code&scope={quote(scope)}&access_type=offline&prompt=consent&state={state_token}'
elif app_key == 'clickup':
client_id = os.getenv('CLICKUP_CLIENT_ID')
if not client_id:
raise HTTPException(status_code=500, detail="ClickUp not configured")
base_url = base_url.rstrip('/')
redirect_uri = f'{base_url}/v2/integrations/clickup/callback'
from urllib.parse import quote
auth_url = (
f'https://app.clickup.com/api?client_id={client_id}&redirect_uri={quote(redirect_uri)}&state={state_token}'
)
else:
raise HTTPException(status_code=400, detail=f"Unsupported integration: {app_key}")
return OAuthUrlResponse(auth_url=auth_url)
class CreateTaskRequest(BaseModel):
"""Request to create a task in an integration"""
title: str = Field(description="Task title/name")
description: Optional[str] = Field(default=None, description="Task description/notes")
due_date: Optional[str] = Field(default=None, description="Due date in ISO format")
class CreateTaskResponse(BaseModel):
"""Response for task creation"""
success: bool
external_task_id: Optional[str] = None
error: Optional[str] = None
@router.post("/v1/task-integrations/{app_key}/tasks", response_model=CreateTaskResponse, tags=['task-integrations'])
async def create_task_via_integration(
app_key: str, request: CreateTaskRequest, uid: str = Depends(auth.get_current_user_uid)
):
"""Create a task in the specified integration using stored credentials."""
# Get integration details
integration = await run_blocking(db_executor, users_db.get_task_integration, uid, app_key)
if not integration or not integration.get('connected'):
raise HTTPException(status_code=404, detail=f"Not connected to {app_key}")
# Validate access token exists
if not integration.get('access_token'):
raise HTTPException(status_code=401, detail=f"No access token for {app_key}")
# Parse due date if provided
due_date = None
if request.due_date:
try:
due_date = datetime.fromisoformat(request.due_date.replace('Z', '+00:00'))
except ValueError:
raise HTTPException(status_code=400, detail="Invalid due_date; expected an ISO 8601 date string")
result = await create_task_internal(
uid=uid,
app_key=app_key,
integration=integration,
title=request.title,
description=request.description,
due_date=due_date,
)
if not result.get("success"):
error_code = result.get("error_code")
error_msg = result.get("error", "Unknown error")
if error_code == "token_refresh_failed":
name = OAUTH_CONFIGS.get(app_key, {'name': app_key}).get('name', app_key)
raise HTTPException(status_code=401, detail=f"{name} token refresh failed. Please reconnect.")
if error_code == "no_access_token":
raise HTTPException(status_code=401, detail=error_msg)
return CreateTaskResponse(
success=result.get("success", False),
external_task_id=result.get("external_task_id"),
error=result.get("error"),
)
# *****************************
# ****** Data Fetching APIs ****
# *****************************
@router.get(
"/v1/task-integrations/asana/workspaces", response_model=AsanaWorkspacesResponse, tags=['task-integrations']
)
async def get_asana_workspaces(uid: str = Depends(auth.get_current_user_uid)):
"""Get user's Asana workspaces"""
data = await run_blocking(db_executor, users_db.get_task_integration, uid, 'asana')
if not data:
raise HTTPException(status_code=404, detail="Asana integration not found")
data = await ensure_valid_oauth_token(uid, 'asana', data)
if not data.get('connected'):
raise HTTPException(status_code=401, detail="Asana token refresh failed. Please reconnect.")
if not data.get('access_token'):
raise HTTPException(status_code=401, detail="Asana not authenticated")
try:
async def _request(client, token):
return await client.get(
'https://app.asana.com/api/1.0/workspaces',
headers={'Authorization': f'Bearer {token}'},
)
response, data, err = await perform_request_with_token_retry(uid, 'asana', data, _request)
if err:
raise HTTPException(status_code=401, detail="Asana authentication expired. Please reconnect.")
if response.status_code == 200:
result = response.json()
return {'workspaces': result.get('data', [])}
else:
raise HTTPException(status_code=response.status_code, detail="Failed to fetch Asana workspaces")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching workspaces: {str(e)}")
@router.get(
"/v1/task-integrations/asana/projects/{workspace_gid}",
response_model=AsanaProjectsResponse,
tags=['task-integrations'],
)
async def get_asana_projects(workspace_gid: str, uid: str = Depends(auth.get_current_user_uid)):
"""Get projects in an Asana workspace"""
data = await run_blocking(db_executor, users_db.get_task_integration, uid, 'asana')
if not data:
raise HTTPException(status_code=404, detail="Asana integration not found")
data = await ensure_valid_oauth_token(uid, 'asana', data)
if not data.get('connected'):
raise HTTPException(status_code=401, detail="Asana token refresh failed. Please reconnect.")
if not data.get('access_token'):
raise HTTPException(status_code=401, detail="Asana not authenticated")
try:
async def _request(client, token):
return await client.get(
f'https://app.asana.com/api/1.0/projects?workspace={workspace_gid}&archived=false&opt_fields=name,gid,owner',
headers={'Authorization': f'Bearer {token}'},
)
response, data, err = await perform_request_with_token_retry(uid, 'asana', data, _request)
if err:
raise HTTPException(status_code=401, detail="Asana authentication expired. Please reconnect.")
if response.status_code == 200:
result = response.json()
return {'projects': result.get('data', [])}
else:
raise HTTPException(status_code=response.status_code, detail="Failed to fetch Asana projects")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching projects: {str(e)}")
@router.get("/v1/task-integrations/clickup/teams", response_model=ClickUpTeamsResponse, tags=['task-integrations'])
async def get_clickup_teams(uid: str = Depends(auth.get_current_user_uid)):
"""Get user's ClickUp teams"""
data = await run_blocking(db_executor, users_db.get_task_integration, uid, 'clickup')
if not data:
raise HTTPException(status_code=404, detail="ClickUp integration not found")
data = await ensure_valid_oauth_token(uid, 'clickup', data)
if not data.get('connected'):
raise HTTPException(status_code=401, detail="ClickUp token refresh failed. Please reconnect.")
if not data.get('access_token'):
raise HTTPException(status_code=401, detail="ClickUp not authenticated")
try:
async def _request(client, token):
return await client.get(
'https://api.clickup.com/api/v2/team',
headers={'Authorization': token},
)
response, data, err = await perform_request_with_token_retry(uid, 'clickup', data, _request)
if err:
raise HTTPException(status_code=401, detail="ClickUp authentication expired. Please reconnect.")
if response.status_code == 200:
result = response.json()
return {'teams': result.get('teams', [])}
else:
raise HTTPException(status_code=response.status_code, detail="Failed to fetch ClickUp teams")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching teams: {str(e)}")
@router.get(
"/v1/task-integrations/clickup/spaces/{team_id}", response_model=ClickUpSpacesResponse, tags=['task-integrations']
)
async def get_clickup_spaces(team_id: str, uid: str = Depends(auth.get_current_user_uid)):
"""Get spaces in a ClickUp team"""
data = await run_blocking(db_executor, users_db.get_task_integration, uid, 'clickup')
if not data:
raise HTTPException(status_code=404, detail="ClickUp integration not found")
data = await ensure_valid_oauth_token(uid, 'clickup', data)
if not data.get('connected'):
raise HTTPException(status_code=401, detail="ClickUp token refresh failed. Please reconnect.")
if not data.get('access_token'):
raise HTTPException(status_code=401, detail="ClickUp not authenticated")
try:
async def _request(client, token):
return await client.get(
f'https://api.clickup.com/api/v2/team/{team_id}/space?archived=false',
headers={'Authorization': token},
)
response, data, err = await perform_request_with_token_retry(uid, 'clickup', data, _request)
if err:
raise HTTPException(status_code=401, detail="ClickUp authentication expired. Please reconnect.")
if response.status_code == 200:
result = response.json()
return {'spaces': result.get('spaces', [])}
else:
raise HTTPException(status_code=response.status_code, detail="Failed to fetch ClickUp spaces")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching spaces: {str(e)}")
@router.get(
"/v1/task-integrations/clickup/lists/{space_id}", response_model=ClickUpListsResponse, tags=['task-integrations']
)
async def get_clickup_lists(space_id: str, uid: str = Depends(auth.get_current_user_uid)):
"""Get lists in a ClickUp space"""
data = await run_blocking(db_executor, users_db.get_task_integration, uid, 'clickup')
if not data:
raise HTTPException(status_code=404, detail="ClickUp integration not found")
data = await ensure_valid_oauth_token(uid, 'clickup', data)
if not data.get('connected'):
raise HTTPException(status_code=401, detail="ClickUp token refresh failed. Please reconnect.")
if not data.get('access_token'):
raise HTTPException(status_code=401, detail="ClickUp not authenticated")
try:
async def _request(client, token):
return await client.get(
f'https://api.clickup.com/api/v2/space/{space_id}/list?archived=false',
headers={'Authorization': token},
)
response, data, err = await perform_request_with_token_retry(uid, 'clickup', data, _request)
if err:
raise HTTPException(status_code=401, detail="ClickUp authentication expired. Please reconnect.")
if response.status_code == 200:
result = response.json()
return {'lists': result.get('lists', [])}
else:
raise HTTPException(status_code=response.status_code, detail="Failed to fetch ClickUp lists")
except HTTPException:
raise
except Exception as e:
raise HTTPException(status_code=500, detail=f"Error fetching lists: {str(e)}")
# *****************************
# ******* OAuth Callbacks *****
# *****************************
class OAuthProviderConfig(BaseModel):
"""Configuration for OAuth provider-specific logic"""
token_endpoint: str
token_request_type: str = "form"
token_request_data: Dict[str, Any]
additional_headers: Dict[str, str] = {}
async def fetch_additional_data(self, client: httpx.AsyncClient, access_token: str) -> Dict[str, Any]:
"""Hook for fetching provider-specific data after token exchange"""
return {}
async def handle_oauth_callback(
request: Request,
app_key: str,
code: Optional[str],
state: Optional[str],
provider_config: OAuthProviderConfig,
) -> HTMLResponse:
"""
Generic OAuth callback handler that works for all providers.
Args:
request: FastAPI request object
app_key: Integration app key (todoist, asana, google_tasks, clickup)
code: Authorization code from OAuth provider
state: State token for CSRF protection
provider_config: Provider-specific configuration
Returns:
HTMLResponse with OAuth callback page
"""
if not code or not state:
return render_oauth_response(request, app_key, success=False, error_type='missing_code')
# Validate state token
state_data = validate_and_consume_oauth_state(state)
if not state_data or state_data.get('app_key') != app_key:
return render_oauth_response(request, app_key, success=False, error_type='invalid_state')
uid = state_data['uid']
try:
client = get_http_client()
if provider_config.token_request_type == "form":
token_response = await client.post(
provider_config.token_endpoint,
headers={
'Content-Type': 'application/x-www-form-urlencoded',
**provider_config.additional_headers,
},
data=provider_config.token_request_data,
)
else: # params
token_response = await client.post(
provider_config.token_endpoint,
params=provider_config.token_request_data,
headers=provider_config.additional_headers,
)
if token_response.status_code == 200:
token_data = token_response.json()
access_token = token_data.get('access_token', '')
refresh_token = token_data.get('refresh_token')
expires_in = token_data.get('expires_in') # Seconds until expiry
if not access_token:
logger.info(f'{app_key}: No access token received in response')
deep_link = f'omi://{app_key}/callback?error=no_access_token'
return render_oauth_response(request, app_key, success=True, redirect_url=deep_link)
integration_data = {
'connected': True,
'access_token': access_token,
}
supports_refresh = app_key in ['google_tasks', 'asana']
if refresh_token and supports_refresh:
integration_data['refresh_token'] = refresh_token
if expires_in and supports_refresh:
expires_at = datetime.now(timezone.utc) + timedelta(seconds=expires_in)
integration_data['expires_at'] = expires_at.isoformat()
try:
additional_data = await provider_config.fetch_additional_data(client, access_token)
integration_data.update(additional_data)
except Exception as e:
logger.error(f'{app_key}: Error fetching additional data: {e}')
# Store in Firebase
try:
await run_blocking(db_executor, users_db.set_task_integration, uid, app_key, integration_data)
logger.info(f'{app_key}: Successfully stored tokens for user {uid}')
except Exception as e:
logger.error(f'{app_key}: Error storing tokens in Firebase: {e}')
deep_link = f'omi://{app_key}/callback?error=storage_failed'
return render_oauth_response(request, app_key, success=True, redirect_url=deep_link)
requires_setup = 'requires_setup=true' if app_key in ['asana', 'clickup'] else ''
deep_link = f'omi://{app_key}/callback?success=true{"&" + requires_setup if requires_setup else ""}'
return render_oauth_response(request, app_key, success=True, redirect_url=deep_link)
else:
logger.error(f'{app_key}: Token exchange failed with HTTP {token_response.status_code}')
deep_link = f'omi://{app_key}/callback?error=token_exchange_failed'
return render_oauth_response(request, app_key, success=True, redirect_url=deep_link)
except Exception as e:
logger.error(f'{app_key}: Unexpected error during OAuth callback: {e}')
deep_link = f'omi://{app_key}/callback?error=server_error'
return render_oauth_response(request, app_key, success=True, redirect_url=deep_link)
@router.get(
'/v2/integrations/todoist/callback',
response_class=HTMLResponse,
tags=['task-integrations', 'oauth'],
)
async def todoist_oauth_callback(
request: Request,
code: Optional[str] = Query(None),
state: Optional[str] = Query(None),
):
"""OAuth callback endpoint for Todoist integration."""
client_id = os.getenv('TODOIST_CLIENT_ID')
client_secret = os.getenv('TODOIST_CLIENT_SECRET')
if not all([client_id, client_secret]):
return render_oauth_response(request, 'todoist', success=False, error_type='config_error')
config = OAuthProviderConfig(
token_endpoint='https://todoist.com/oauth/access_token',
token_request_type='form',
token_request_data={
'client_id': client_id,
'client_secret': client_secret,
'code': code,
},
)
return await handle_oauth_callback(request, 'todoist', code, state, config)
@router.get(
'/v2/integrations/asana/callback',
response_class=HTMLResponse,
tags=['task-integrations', 'oauth'],
)
async def asana_oauth_callback(
request: Request,
code: Optional[str] = Query(None),
state: Optional[str] = Query(None),
):
"""OAuth callback endpoint for Asana integration."""
client_id = os.getenv('ASANA_CLIENT_ID')
client_secret = os.getenv('ASANA_CLIENT_SECRET')
base_url = os.getenv('BASE_API_URL')
if not all([client_id, client_secret, base_url]):
return render_oauth_response(request, 'asana', success=False, error_type='config_error')
# Normalize base_url: remove trailing slash to prevent redirect URI mismatches
base_url = base_url.rstrip('/')
redirect_uri = f'{base_url}/v2/integrations/asana/callback'
class AsanaConfig(OAuthProviderConfig):
async def fetch_additional_data(self, client: httpx.AsyncClient, access_token: str) -> Dict[str, Any]:
"""Fetch Asana user GID"""
try:
user_response = await client.get(
'https://app.asana.com/api/1.0/users/me',
headers={'Authorization': f'Bearer {access_token}'},
)
if user_response.status_code == 200:
user_data = user_response.json()
user_gid = user_data.get('data', {}).get('gid')
return {'user_gid': user_gid} if user_gid else {}
except Exception as e:
logger.error(f'asana: Failed to fetch user GID: {e}')
return {}
config = AsanaConfig(
token_endpoint='https://app.asana.com/-/oauth_token',
token_request_type='form',
token_request_data={
'grant_type': 'authorization_code',
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'code': code,
},
)
return await handle_oauth_callback(request, 'asana', code, state, config)
@router.get(
'/v2/integrations/google-tasks/callback',
response_class=HTMLResponse,
tags=['task-integrations', 'oauth'],
)
async def google_tasks_oauth_callback(
request: Request,
code: Optional[str] = Query(None),
state: Optional[str] = Query(None),
):
"""OAuth callback endpoint for Google Tasks integration."""
client_id = os.getenv('GOOGLE_TASKS_CLIENT_ID')
client_secret = os.getenv('GOOGLE_TASKS_CLIENT_SECRET')
base_url = os.getenv('BASE_API_URL')
if not all([client_id, client_secret, base_url]):
return render_oauth_response(request, 'google_tasks', success=False, error_type='config_error')
# Normalize base_url: remove trailing slash to prevent redirect URI mismatches
base_url = base_url.rstrip('/')
redirect_uri = f'{base_url}/v2/integrations/google-tasks/callback'
class GoogleTasksConfig(OAuthProviderConfig):
async def fetch_additional_data(self, client: httpx.AsyncClient, access_token: str) -> Dict[str, Any]:
"""Fetch default Google Tasks list"""
try:
lists_response = await client.get(
'https://tasks.googleapis.com/tasks/v1/users/@me/lists',
headers={'Authorization': f'Bearer {access_token}'},
)
if lists_response.status_code == 200:
lists_data = lists_response.json()
items = lists_data.get('items', [])
if items:
return {
'default_list_id': items[0].get('id'),
'default_list_title': items[0].get('title'),
}
except Exception as e:
logger.error(f'google_tasks: Failed to fetch task lists: {e}')
return {}
config = GoogleTasksConfig(
token_endpoint='https://oauth2.googleapis.com/token',
token_request_type='form',
token_request_data={
'code': code,
'client_id': client_id,
'client_secret': client_secret,
'redirect_uri': redirect_uri,
'grant_type': 'authorization_code',
},
)
return await handle_oauth_callback(request, 'google_tasks', code, state, config)
@router.get(
'/v2/integrations/clickup/callback',
response_class=HTMLResponse,
tags=['task-integrations', 'oauth'],
)
async def clickup_oauth_callback(
request: Request,
code: Optional[str] = Query(None),
state: Optional[str] = Query(None),
):
"""OAuth callback endpoint for ClickUp integration."""
client_id = os.getenv('CLICKUP_CLIENT_ID')
client_secret = os.getenv('CLICKUP_CLIENT_SECRET')
if not all([client_id, client_secret]):
return render_oauth_response(request, 'clickup', success=False, error_type='config_error')
config = OAuthProviderConfig(
token_endpoint='https://api.clickup.com/api/v2/oauth/token',
token_request_type='params',
token_request_data={
'client_id': client_id,
'client_secret': client_secret,
'code': code,
},
)
return await handle_oauth_callback(request, 'clickup', code, state, config)
@router.on_event("shutdown")
async def shutdown_http_client():
"""Cleanup HTTP client on app shutdown."""
await close_http_client()