Overview
The Email OAuth integration allows users to connect their Gmail and Outlook accounts to the email agent. This document explains how the OAuth flow works and what’s been implemented.OAuth Flow Architecture
Backend Implementation
Gmail OAuth Endpoints
POST /email_bot/gmail/oauth/init
Initializes the Gmail OAuth flow.
Request:
- Creates a secure state token with user context
- Stores state in memory for validation
- Builds Composio authorization URL
- Returns URL for frontend to redirect to
GET /email_bot/gmail/oauth/callback
Handles the OAuth callback from Composio.
Query Parameters:
state: The state token from initconnected_account_id: Composio account IDstatus: OAuth status (success/error)error: Error message (if any)
- Validates state token
- Checks state expiration (15 min timeout)
- Gets Gmail email address from Composio using
GMAIL_GET_PROFILEtool - Stores account in
email_oauth_tokenstable - Updates
email_configwith connected email - Redirects back to frontend with result
- Success:
{origin_url}?oauth=success&email={email} - Error:
{origin_url}?oauth=error&message={error}
Outlook OAuth Endpoints
POST /email_bot/outlook/oauth/init
Initializes the Outlook OAuth flow (same pattern as Gmail).
GET /email_bot/outlook/oauth/callback
Handles OAuth callback for Outlook using OUTLOOK_OUTLOOK_GET_PROFILE tool.
Database Schema
email_oauth_tokens Table
Stores OAuth credentials for connected accounts.
user_id: Reference to the user who connected the accountprovider:'google'for Gmail,'microsoft'for Outlookemail: The connected email addresscomposio_account_id: Composio’s account identifier- Unique constraint ensures one account per email per provider
email_config Table
Stores user email configuration and preferences.
connected_emails Format:
Frontend Implementation
OAuth Integration
The frontend automatically handles both Gmail and Outlook OAuth callbacks. Location:/email-agent-settings page
Connect Gmail Button
Connect Outlook Button
OAuth Callback Handler
Runs on component mount to detect OAuth redirects:Connected Emails Display
Shows all connected Gmail and Outlook accounts with provider logos:Security Features
State Token Security
- Generated with user context: Includes user ID and timestamp
- Base64 encoded: URL-safe transmission
- Server-side storage: Validated against stored states
- 15-minute expiration: Prevents replay attacks
- Single-use: Deleted after callback processing
Authorization
- JWT authentication: All endpoints require valid JWT token
- User isolation: Can only access own OAuth flows
- Token extraction: User ID extracted from JWT
- Firm-level access: RLS policies ensure data isolation
Composio Integration
- Entity-based auth: User ID as Composio entity
- Account ID storage: Store Composio IDs, not raw tokens
- Automatic refresh: Composio handles token refresh
- Secure callbacks: Validate all callback parameters
Environment Variables
Backend (.env)
Frontend (.env.local)
Testing the OAuth Flow
Manual Testing Steps
1
Start Backend Server
{"status": "healthy"}2
Start Frontend Server
3
Navigate to Settings
Go to
http://localhost:3000/email-agent-settings and log in4
Click Connect Gmail/Outlook
Button should show loading state, then redirect to OAuth provider
5
Grant Permissions
- Select your Gmail or Outlook account
- Grant required permissions
- Click “Allow” or “Accept”
6
Verify Redirect
- Should redirect back to settings page
- Success toast should appear
- Email should appear in connected accounts list
- URL should be clean (no query parameters)
Expected Behavior
- Success Flow
- Error Flow
✅ Success Flow:
- Click “Connect Gmail/Outlook” → Loading spinner appears
- Redirect to Google/Microsoft OAuth → Grant permissions
- Redirect back to settings → Green success toast
- Email appears in “Connected Email Accounts”
- URL is clean (no
?oauth=success&email=...) - Provider logo displays correctly
Troubleshooting
Failed to initialize OAuth flow
Failed to initialize OAuth flow
Cause: Backend endpoint not responding or unauthorizedSolution:
- Verify backend is running on
localhost:8000 - Check JWT token is valid
- Ensure
COMPOSIO_API_KEYis set in backend.env - Check browser console for error messages
Invalid or expired state
Invalid or expired state
Cause: State token expired (> 15 minutes) or tampered withSolution:
- Try connecting again (state expires after 15 minutes)
- Check system clock is synchronized
- Ensure cookies/localStorage aren’t blocked
Failed to get authorized email
Failed to get authorized email
Email not appearing in list
Email not appearing in list
Cause: Database update failed or frontend not refreshingSolution:
- Check Supabase connection in backend
- Verify table permissions allow INSERT/UPDATE
- Check browser console for API errors
- Try refreshing the page manually
CORS error when calling API
CORS error when calling API
Cause: Backend CORS not configured for frontend originSolution:
Gmail vs Outlook Comparison
| Feature | Gmail | Outlook |
|---|---|---|
| Init Endpoint | /email_bot/gmail/oauth/init | /email_bot/outlook/oauth/init |
| Callback Endpoint | /email_bot/gmail/oauth/callback | /email_bot/outlook/oauth/callback |
| Provider Name | google | microsoft |
| Auth Config Env | COMPOSIO_GMAIL_AUTH_CONFIG_ID | COMPOSIO_OUTLOOK_AUTH_CONFIG_ID |
| Profile Tool | GMAIL_GET_PROFILE | OUTLOOK_OUTLOOK_GET_PROFILE |
| Email Field | emailAddress | mail |
| Logo | /gmail_new_logo_icon_159149.png | /png-transparent-outlook-logo.png |
| OAuth Callback | Same handler | Same handler |
What’s Next
Once OAuth is working, you can:- Disconnect emails: Add functionality to remove connected accounts
- Token refresh monitoring: Track and alert on token expiration
- Connection health checks: Verify tokens are still valid
- Send emails: Use Composio’s email sending capabilities
- Email syncing: Fetch emails and sync to database
- Email automation: Build automated email workflows
Summary
✅ What’s Working:- Gmail OAuth initialization and callback
- Outlook OAuth initialization and callback
- Secure state management (15-min expiration)
- Database persistence in Supabase
- Frontend toast notifications
- URL cleanup after redirect
- Connected emails display with provider logos
- Comprehensive error handling
