dify/web/hooks/use-oauth.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-06-19 16:09:05 +08:00
'use client'
import { useEffect } from 'react'
import { useSearchParams } from 'next/navigation'
export const useOAuthCallback = () => {
const searchParams = useSearchParams()
useEffect(() => {
2025-06-23 11:08:56 +08:00
const MCPProviderID = searchParams.get('mcp_provider_id')
2025-06-19 16:09:05 +08:00
2025-06-23 11:08:56 +08:00
if (MCPProviderID && window.opener) {
2025-06-19 16:09:05 +08:00
window.opener.postMessage({
type: 'oauth_callback',
payload: {
2025-06-23 11:08:56 +08:00
state: MCPProviderID,
2025-06-19 16:09:05 +08:00
},
}, '*')
window.close()
}
}, [searchParams])
}
2025-06-23 11:08:56 +08:00
export const openOAuthPopup = (url: string, callback: (state: string) => void) => {
2025-06-19 16:09:05 +08:00
const width = 600
const height = 600
const left = window.screenX + (window.outerWidth - width) / 2
const top = window.screenY + (window.outerHeight - height) / 2
const popup = window.open(
url,
'OAuth',
`width=${width},height=${height},left=${left},top=${top},scrollbars=yes`,
)
const handleMessage = (event: MessageEvent) => {
if (event.data?.type === 'oauth_callback') {
window.removeEventListener('message', handleMessage)
2025-06-23 11:08:56 +08:00
const { state } = event.data.payload
callback(state)
2025-06-19 16:09:05 +08:00
}
}
window.addEventListener('message', handleMessage)
return popup
}