Spaces:
Running
Running
// Utility for OAuth authentication with MCP servers | |
// Usage: import { authenticateWithOAuth } from "./oauth"; | |
export async function authenticateWithOAuth({ | |
authUrl, | |
clientId, | |
redirectUri, | |
scope = "openid profile", | |
}: { | |
authUrl: string; | |
clientId: string; | |
redirectUri: string; | |
scope?: string; | |
}): Promise<string> { | |
// Open a popup for OAuth login | |
const state = Math.random().toString(36).substring(2); | |
const url = `${authUrl}?response_type=token&client_id=${encodeURIComponent( | |
clientId | |
)}&redirect_uri=${encodeURIComponent(redirectUri)}&scope=${encodeURIComponent( | |
scope | |
)}&state=${state}`; | |
return new Promise((resolve, reject) => { | |
const popup = window.open(url, "oauth-login", "width=500,height=700"); | |
if (!popup) return reject("Popup blocked"); | |
const interval = setInterval(() => { | |
try { | |
if (!popup || popup.closed) { | |
clearInterval(interval); | |
reject("Popup closed"); | |
} | |
// Check for access token in URL | |
const href = popup.location.href; | |
if (href.startsWith(redirectUri)) { | |
const hash = popup.location.hash; | |
const params = new URLSearchParams(hash.substring(1)); | |
const token = params.get("access_token"); | |
if (token) { | |
clearInterval(interval); | |
popup.close(); | |
resolve(token); | |
} else { | |
clearInterval(interval); | |
popup.close(); | |
reject("No access token found"); | |
} | |
} | |
} catch (e) { | |
// Ignore cross-origin errors until redirect | |
} | |
}, 500); | |
}); | |
} | |