Skip to content

OpenRAG is a comprehensive, single package Retrieval-Augmented Generation platform built on Langflow, Docling, and Opensearch.

Python

Added first version of connection id and return url

Lucas Oliveira9c11d217fa95
diff --git a/frontend/app/api/mutations/useConnectConnectorMutation.ts b/frontend/app/api/mutations/useConnectConnectorMutation.ts
index 6e0faf4b8..0701e1125 100644
--- a/frontend/app/api/mutations/useConnectConnectorMutation.ts
+++ b/frontend/app/api/mutations/useConnectConnectorMutation.ts
@@ -4,6 +4,7 @@ import type { Connector } from "../queries/useGetConnectorsQuery";
interface ConnectResponse {
connection_id: string;
+ public_return_url?: string;
oauth_config?: {
authorization_endpoint: string;
client_id: string;
@@ -68,6 +69,9 @@ export const useConnectConnectorMutation = () => {
localStorage.setItem("connecting_connector_type", connector.type);
localStorage.setItem("auth_purpose", "data_source");
+ const returnUrl = result.public_return_url || window.location.origin;
+ const state = `id=${result.connection_id}&return=${encodeURIComponent(returnUrl)}`;
+
const authUrl =
`${result.oauth_config.authorization_endpoint}?` +
`client_id=${result.oauth_config.client_id}&` +
@@ -78,7 +82,7 @@ export const useConnectConnectorMutation = () => {
)}&` +
`access_type=offline&` +
`prompt=select_account&` +
- `state=${result.connection_id}`;
+ `state=${encodeURIComponent(state)}`;
window.location.href = authUrl;
} else {
diff --git a/frontend/app/auth/callback/page.tsx b/frontend/app/auth/callback/page.tsx
index 55cd3a4d3..7156570d8 100644
--- a/frontend/app/auth/callback/page.tsx
+++ b/frontend/app/auth/callback/page.tsx
@@ -80,13 +80,31 @@ function AuthCallbackContent() {
}
// Send callback data to backend
+ const stateParam = searchParams.get("state");
+ let parsedConnectionId = finalConnectorId;
+ let stateReturnUrl = null;
+
+ if (stateParam && stateParam.includes("id=")) {
+ try {
+ const params = new URLSearchParams(stateParam);
+ parsedConnectionId = params.get("id") || finalConnectorId;
+ stateReturnUrl = params.get("return");
+ console.log("Parsed state parameter:", {
+ parsedConnectionId,
+ stateReturnUrl,
+ });
+ } catch (e) {
+ console.error("Failed to parse state parameter", e);
+ }
+ }
+
const response = await fetch("/api/auth/callback", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
- connection_id: finalConnectorId,
+ connection_id: parsedConnectionId,
authorization_code: code,
state: state,
}),
@@ -101,8 +119,9 @@ function AuthCallbackContent() {
// App authentication - refresh auth context and redirect to home/original page
await refreshAuth();
- // Get redirect URL from login page
- const redirectTo = searchParams.get("redirect") || "/chat";
+ // Get redirect URL from state, search params, or default
+ const redirectTo =
+ stateReturnUrl || searchParams.get("redirect") || "/chat";
// Clean up localStorage
localStorage.removeItem("connecting_connector_id");
diff --git a/frontend/contexts/auth-context.tsx b/frontend/contexts/auth-context.tsx
index fd25302e0..fc1794b14 100644
--- a/frontend/contexts/auth-context.tsx
+++ b/frontend/contexts/auth-context.tsx
@@ -150,6 +150,9 @@ export function AuthProvider({ children }: AuthProviderProps) {
),
});
+ const returnUrl = result.public_return_url || window.location.origin;
+ const state = `id=${result.connection_id}&return=${encodeURIComponent(returnUrl)}`;
+
const authUrl =
`${result.oauth_config.authorization_endpoint}?` +
`client_id=${result.oauth_config.client_id}&` +
@@ -158,7 +161,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
`redirect_uri=${encodeURIComponent(result.oauth_config.redirect_uri)}&` +
`access_type=offline&` +
`prompt=select_account&` +
- `state=${result.connection_id}`;
+ `state=${encodeURIComponent(state)}`;
console.log("Redirecting to OAuth URL:", authUrl);
window.location.href = authUrl;
diff --git a/src/config/settings.py b/src/config/settings.py
index 26514d658..fae7525cf 100644
--- a/src/config/settings.py
+++ b/src/config/settings.py
@@ -110,6 +110,9 @@ WEBHOOK_BASE_URL = os.getenv(
"WEBHOOK_BASE_URL"
) # No default - must be explicitly configured
+# Public return URL for OAuth flows (Broker redirect)
+PUBLIC_RETURN_URL = os.getenv("PUBLIC_RETURN_URL")
+
# OpenSearch configuration
VECTOR_DIM = 1536
KNN_EF_CONSTRUCTION = 100
diff --git a/src/connectors/google_drive/oauth.py b/src/connectors/google_drive/oauth.py
index 8a46be1e8..d77ddfb63 100644
--- a/src/connectors/google_drive/oauth.py
+++ b/src/connectors/google_drive/oauth.py
@@ -112,7 +112,9 @@ class GoogleDriveOAuth:
from utils.encryption import write_encrypted_file
await write_encrypted_file(self.token_file, json.dumps(token_data))
- def create_authorization_url(self, redirect_uri: str) -> str:
+ def create_authorization_url(
+ self, redirect_uri: str, state: Optional[str] = None
+ ) -> str:
"""Create authorization URL for OAuth flow"""
# Create flow from client credentials directly
client_config = {
@@ -128,11 +130,15 @@ class GoogleDriveOAuth:
client_config, scopes=self.SCOPES, redirect_uri=redirect_uri
)
- auth_url, _ = flow.authorization_url(
- access_type="offline",
- include_granted_scopes="true",
- prompt="consent", # Force consent to get refresh token
- )
+ kwargs = {
+ "access_type": "offline",
+ "include_granted_scopes": "true",
+ "prompt": "consent", # Force consent to get refresh token
+ }
+ if state:
+ kwargs["state"] = state
+
+ auth_url, _ = flow.authorization_url(**kwargs)
# Store flow state for later use
self._flow_state = flow.state
diff --git a/src/services/auth_service.py b/src/services/auth_service.py
index 61dd79245..8d4e6dd88 100644
--- a/src/services/auth_service.py
+++ b/src/services/auth_service.py
@@ -6,7 +6,7 @@ import logging
from datetime import datetime, timedelta
from typing import Optional
import asyncio
-
+import os
from config.settings import WEBHOOK_BASE_URL, is_no_auth_mode
from fastapi import HTTPException
@@ -54,7 +54,7 @@ class AuthService:
if IBM_AUTH_ENABLED and purpose == "app_auth":
raise HTTPException(
status_code=409,
- detail="IBM AMS authentication is active. Login is handled via the IBM Watsonx Data session cookie."
+ detail="IBM AMS authentication is active. Login is handled via the IBM Watsonx Data session cookie.",
)
# Check if we're in no-auth mode
@@ -116,7 +116,6 @@ class AuthService:
return await self._init_direct_connection(connector_type, connection_id)
# Get OAuth configuration from connector and OAuth classes
- import os
# Map connector types to their connector and OAuth classes
connector_class_map = {
@@ -161,16 +160,18 @@ class AuthService:
f"Set {client_key} and {secret_key} in the environment."
)
- oauth_config = {
- "client_id": client_id,
- "scopes": scopes,
- "redirect_uri": redirect_uri,
- "authorization_endpoint": auth_endpoint,
- "token_endpoint": token_endpoint,
+ return {
+ "connection_id": connection_id,
+ "oauth_config": {
+ "client_id": client_id,
+ "scopes": scopes,
+ "redirect_uri": redirect_uri,
+ "authorization_endpoint": auth_endpoint,
+ "token_endpoint": token_endpoint,
+ },
+ "public_return_url": os.getenv("PUBLIC_RETURN_URL"),
}
- return {"connection_id": connection_id, "oauth_config": oauth_config}
-
async def _init_direct_connection(
self, connector_type: str, connection_id: str
) -> dict:
@@ -215,9 +216,7 @@ class AuthService:
await self.connector_service.connection_manager.delete_connection(
connection_id
)
- raise ValueError(
- f"Failed to connect {connector_type}: {exc}"
- ) from exc
+ raise ValueError(f"Failed to connect {connector_type}: {exc}") from exc
return {
"connection_id": connection_id,
@@ -331,6 +330,7 @@ class AuthService:
# Save tokens to file
token_file_path = connection_config.config["token_file"]
from utils.encryption import write_encrypted_file
+
await write_encrypted_file(token_file_path, json.dumps(token_file_data))
# Route based on purpose
@@ -593,4 +593,8 @@ class AuthService:
return user_data
else:
- return {"authenticated": False, "ibm_auth_mode": IBM_AUTH_ENABLED, "user": None}
+ return {
+ "authenticated": False,
+ "ibm_auth_mode": IBM_AUTH_ENABLED,
+ "user": None,
+ }