Overview
The gmail-disconnect endpoint handles the disconnection of a Gmail account from Money Tracker. It safely removes OAuth tokens, stops Gmail Watch subscriptions, and preserves existing transaction data.Endpoint
Authentication
Required: User must be authenticated with a valid session token.Request
Path Parameters
The ID of the OAuth connection to disconnect (from
user_oauth_tokens table)cURL
Response
Success Response (200)
Indicates successful disconnection
Confirmation message
Success Response
Error Responses
404 Not Found - Connection not found or user doesn’t own it:Disconnection Process
When a Gmail account is disconnected, the function performs several steps to safely remove the connection:Verify Ownership
Confirms the user owns the OAuth connection by checking
user_id matches the authenticated user.Check Multi-User Accounts
Determines if other users are connected to the same Gmail account. If multiple users share the account, the watch is preserved for them.
Stop Gmail Watch (if last user)
If this is the last user connected to this Gmail account, makes a
POST request to Google’s API to stop the watch:Delete Watch Records
Removes Gmail watch entries from the
gmail_watches table. If other users are still connected, only removes watches for the current user.Soft Delete Token
Marks the OAuth token as inactive instead of deleting it:
- Sets
is_active = false - Clears
expires_at - Updates
updated_attimestamp
Multi-User Behavior
Money Tracker supports multiple users connecting to the same Gmail account. The disconnect logic handles this gracefully:| Scenario | Watch Behavior | Watch Records Deleted |
|---|---|---|
| Last user disconnecting | Gmail Watch stopped | All records for that email |
| Other users still connected | Gmail Watch preserved | Only current user’s records |
Data Preservation
Important data retention behavior:- Transactions: All imported transactions are preserved
- OAuth tokens: Soft-deleted (marked inactive, not removed)
- Gmail watches: Deleted for the user
- Pub/Sub subscriptions: Remain active if other users are connected
Users can reconnect the same Gmail account later, and historical transactions will still be available.
Implementation Notes
Security
- Uses
SUPABASE_SERVICE_ROLE_KEYto bypass RLS for multi-user checks - Verifies user ownership before allowing disconnection
- Prevents users from disconnecting other users’ connections
Error Handling
The function gracefully handles cases where:- The Gmail Watch may not exist (already stopped)
- The Google API is unavailable
- The access token is expired
Logging
Detailed logs are written to help debug disconnection issues:Frontend Integration
The frontend calls this endpoint via thegmailService:
Related Functions
- auth-start - Connect a Gmail account
- auth-callback - Complete OAuth flow
- gmail-webhook - Process emails