Beautiful Open-Source Form Builder
Enhance OAuth flow and component interactions
JhumanJ2e6304f7ce8d
diff --git a/api/app/Service/OAuth/OAuthFlowOrchestrator.php b/api/app/Service/OAuth/OAuthFlowOrchestrator.phpindex b6eaf78df..7ec2bdce1 100644--- a/api/app/Service/OAuth/OAuthFlowOrchestrator.php+++ b/api/app/Service/OAuth/OAuthFlowOrchestrator.php@@ -108,7 +108,7 @@ class OAuthFlowOrchestrator// Clear the context after use$this->contextService->clearContext($stateToken);- return $this->handleIntent($intent, $providerService, $userData, $inviteToken, $invitedEmail);+ return $this->handleIntent($intent, $providerService, $userData, $inviteToken, $invitedEmail, $context);}/**@@ -147,7 +147,8 @@ class OAuthFlowOrchestratorOAuthProviderService $providerService,array $userData,?string $inviteToken = null,- ?string $invitedEmail = null+ ?string $invitedEmail = null,+ ?array $context = null): array {return match ($intent) {self::INTENT_AUTH => $this->handleAuthenticationFlow(@@ -158,7 +159,8 @@ class OAuthFlowOrchestrator),self::INTENT_INTEGRATION => $this->handleIntegrationFlow($providerService,- $userData+ $userData,+ $context),default => abort(400, 'Invalid intent')};@@ -190,7 +192,7 @@ class OAuthFlowOrchestrator/*** Handle integration flow (connect OAuth provider to existing user)*/- private function handleIntegrationFlow(OAuthProviderService $providerService, array $userData): array+ private function handleIntegrationFlow(OAuthProviderService $providerService, array $userData, ?array $context = null): array{if (!Auth::check()) {abort(401, 'Authentication required for integration connections');@@ -206,8 +208,8 @@ class OAuthFlowOrchestrator$userData);- // Get cached context for additional response data- $context = $this->contextService->getContext() ?? [];+ // Use the passed context to get response data+ $context = $context ?? [];return ['provider' => OAuthProviderResource::make($oauthProvider),diff --git a/client/components/pages/auth/components/QuickRegister.vue b/client/components/pages/auth/components/QuickRegister.vueindex 810d4cd20..a4c979eb1 100644--- a/client/components/pages/auth/components/QuickRegister.vue+++ b/client/components/pages/auth/components/QuickRegister.vue@@ -110,11 +110,11 @@ onMounted(() => {afterLoginMessage.listen(() => {afterQuickLogin()})-- // Reset the unauthorized error flag when component is unmounted- onUnmounted(() => {- appStore.isUnauthorizedError = false- })+})++// Reset the unauthorized error flag when component is unmounted+onUnmounted(() => {+ appStore.isUnauthorizedError = false})// Handle social login completiondiff --git a/client/components/pages/forms/create/CreateFormBaseModal.vue b/client/components/pages/forms/create/CreateFormBaseModal.vueindex b7c468b70..e208ee2b4 100644--- a/client/components/pages/forms/create/CreateFormBaseModal.vue+++ b/client/components/pages/forms/create/CreateFormBaseModal.vue@@ -253,12 +253,8 @@ function selectStyle(style) {if (style === 'focused') {workingFormStore.content.size = 'lg'// Ensure navigation arrows are enabled by default in focused mode- if (!workingFormStore.content.settings) {- workingFormStore.content.settings = {}- }- if (workingFormStore.content.settings.navigation_arrows === undefined) {- workingFormStore.content.settings.navigation_arrows = true- }+ const currentSettings = workingFormStore.content.settings ?? {}+ workingFormStore.content.settings = { ...currentSettings, navigation_arrows: true }// Seed first block image to highlight focused modeseedFocusedFirstBlockImage(workingFormStore.content)}diff --git a/client/components/provider/widget/TelegramWidget.vue b/client/components/provider/widget/TelegramWidget.vueindex 703b5da04..90e102d0f 100644--- a/client/components/provider/widget/TelegramWidget.vue+++ b/client/components/provider/widget/TelegramWidget.vue@@ -49,7 +49,8 @@ const handleAuth = () => {window.Telegram.Login.auth({ bot_id: botId.value, request_access: 'write' },(data) => {- emit('auth-data', data)+ // Include intent for integration flow+ emit('auth-data', { ...data, intent: 'integration' })})} else {diff --git a/client/components/users/settings/ConnectionModal.vue b/client/components/users/settings/ConnectionModal.vueindex 4bece208d..610891fb1 100644--- a/client/components/users/settings/ConnectionModal.vue+++ b/client/components/users/settings/ConnectionModal.vue@@ -90,11 +90,11 @@ const loading = ref(false)const showWidgetModal = ref(false)const selectedService = ref(null)const alert = useAlert()+const windowMessage = useWindowMessage(WindowMessageTypes.OAUTH_PROVIDER_CONNECTED)+// Listen for OAuth completion to close modal and refresh-onMounted(() => {- const windowMessage = useWindowMessage(WindowMessageTypes.OAUTH_PROVIDER_CONNECTED)-+onMounted(() => {windowMessage.listen((_event) => {// OAuth connection completed, close modal and refreshloading.value = falsediff --git a/client/components/users/settings/ProviderWidgetModal.vue b/client/components/users/settings/ProviderWidgetModal.vueindex 7399a3ad4..5c35f63f0 100644--- a/client/components/users/settings/ProviderWidgetModal.vue+++ b/client/components/users/settings/ProviderWidgetModal.vue@@ -87,7 +87,10 @@ const handleAuthData = (data) => {return}- widgetCallbackMutation.mutateAsync({ service: props.service.name, data }).then((response) => {+ // Ensure intent is provided for widget callbacks+ const payload = { ...data, intent: data?.intent || 'integration' }++ widgetCallbackMutation.mutateAsync({ service: props.service.name, data: payload }).then((response) => {if (response.intention) {router.push(response.intention)} else {diff --git a/client/composables/query/useOAuth.js b/client/composables/query/useOAuth.jsindex 4feb96ba2..35b9b93bb 100644--- a/client/composables/query/useOAuth.js+++ b/client/composables/query/useOAuth.js@@ -48,6 +48,39 @@ export function useOAuth() {alert.error(message ?? "An error occurred while connecting an account")}+ // Popup utilities+ const popupFeatures = 'width=600,height=700,left=100,top=100,resizable=yes,scrollbars=yes'++ const preOpenPopupIfNeeded = (shouldOpenInNewTab, service) => {+ if (!shouldOpenInNewTab) return null+ const popupWindow = window.open('', 'oauth_popup_' + service, popupFeatures)+ if (!popupWindow) {+ alert.error('Popup was blocked. Please allow popups and try again.')+ return null+ }+ try { popupWindow.document.title = 'Connecting…' } catch { /* ignore */ }+ return popupWindow+ }++ const navigatePopupOrFallback = (popupWindow, targetUrl, service) => {+ if (popupWindow && !popupWindow.closed) {+ try { popupWindow.location.replace(targetUrl) } catch { popupWindow.location.href = targetUrl }+ return true+ }+ const fallbackPopup = window.open(targetUrl, 'oauth_popup_' + service, popupFeatures)+ if (!fallbackPopup) {+ alert.error('Popup was blocked. Please allow popups and try again.')+ return false+ }+ return true+ }++ const safelyClosePopup = (popupWindow) => {+ if (popupWindow && !popupWindow.closed) {+ try { popupWindow.close() } catch { /* ignore */ }+ }+ }+// Queriesconst providers = (options = {}) => {return useQuery({@@ -78,11 +111,14 @@ export function useOAuth() {// Enhanced connect method with redirect/newtab/autoClose supportconst connect = (service, redirect = false, newtab = false, autoClose = false) => {const serviceConfig = getService(service)+if (serviceConfig && serviceConfig.auth_type && serviceConfig.auth_type !== 'redirect') {return Promise.resolve()}const intention = redirect ? new URL(window.location.href).pathname : undefined+ // If opening in new tab, open synchronously to avoid popup blockers+ const popupWindow = preOpenPopupIfNeeded(newtab, service)return oauthApi.connect(service, {...(intention && { intention }),@@ -90,12 +126,14 @@ export function useOAuth() {}).then((data) => {if (newtab) {- window.open(data.url, '_blank')+ navigatePopupOrFallback(popupWindow, data.url, service)} else {window.location.href = data.url}}).catch((error) => {+ // If we opened a window but failed to get URL, close the placeholder to avoid dangling blank window+ safelyClosePopup(popupWindow)handleOAuthError(error)})}@@ -104,6 +142,9 @@ export function useOAuth() {const guestConnect = (service, redirect = false, additionalData = {}) => {const intention = new URL(window.location.href).pathname+ // Open synchronously to avoid popup blockers+ const popupWindow = preOpenPopupIfNeeded(true, service)+return oauthApi.redirect(service, {...redirect ? { intention } : {},...additionalData@@ -113,10 +154,10 @@ export function useOAuth() {if (additionalData.invite_token) {localStorage.setItem('oauth_invite_token', additionalData.invite_token)}-- window.open(data.url, '_blank')+ navigatePopupOrFallback(popupWindow, data.url, service)}).catch((error) => {+ safelyClosePopup(popupWindow)handleOAuthError(error)})}diff --git a/client/composables/useWindowMessage.js b/client/composables/useWindowMessage.jsindex f25d1a7b6..fc5914121 100644--- a/client/composables/useWindowMessage.js+++ b/client/composables/useWindowMessage.js@@ -4,6 +4,8 @@* Provides a consistent interface for cross-window/iframe communication*/+import { ref, onUnmounted } from 'vue'+// Define common message types as constantsexport const WindowMessageTypes = {LOGIN_COMPLETE: 'login-complete',@@ -26,11 +28,11 @@ export const useWindowMessage = (messageType = null) => {/*** Add a listener for a specific message type*- * @param {string} eventType - The type of message to listen for (defaults to constructor value)* @param {Function} callback - The callback function to call when the message is received* @param {Object} options - Options for the listener- * @param {boolean} options.useMessageChannel - Whether to expect and use MessageChannel ports in the event+ * @param {boolean} options.useMessageChannel - Ignored; maintained for API compatibility* @param {boolean} options.acknowledge - Whether to automatically acknowledge the message+ * @param {string|null} eventType - Override event type (defaults to constructor value)*/const listen = (callback, options = {}, eventType = null) => {const targetEventType = eventType || messageType@@ -40,37 +42,46 @@ export const useWindowMessage = (messageType = null) => {}const {+ // kept for API compatibility; no effect with BroadcastChanneluseMessageChannel = true,acknowledge = true} = optionsconst acknowledgmentName = deriveAcknowledgmentName(targetEventType)-++ // Create a BroadcastChannel per message type+ let channel+ try {+ channel = new BroadcastChannel(targetEventType)+ } catch (err) {+ console.error('BroadcastChannel is not supported in this environment', err)+ return+ }+const handler = (event) => {- // For simple messages- if (!useMessageChannel && event.data === targetEventType) {- callback(event)- return- }-- // For MessageChannel messages- if (useMessageChannel && event.data === targetEventType && event.ports && event.ports.length > 0) {- // Send acknowledgement if requested- if (acknowledge && event.ports[0]) {- event.ports[0].postMessage(acknowledgmentName)+ // Only react to our expected payload (the message name string)+ if (event && event.data === targetEventType) {+ // Send acknowledgement if requested (best-effort)+ if (acknowledge) {+ try {+ const ackChannel = new BroadcastChannel(acknowledgmentName)+ ackChannel.postMessage(acknowledgmentName)+ // Close quickly to avoid leaks+ setTimeout(() => {+ try { ackChannel.close() } catch { /* ignore */ }+ }, 50)+ } catch (e) {+ // ignore ack failures+ }}-- // Call the callback with the eventcallback(event)- return}}-- // Add the listener to the window- window.addEventListener('message', handler)-- // Store the handler for cleanup- listeners.value.set(targetEventType, handler)++ channel.onmessage = handler++ // Store for cleanup (channel + handler)+ listeners.value.set(targetEventType, { channel, handler })// Return a function to remove the listenerreturn () => stopListening(targetEventType)@@ -88,30 +99,30 @@ export const useWindowMessage = (messageType = null) => {return}- const handler = listeners.value.get(targetEventType)- if (handler) {- window.removeEventListener('message', handler)- listeners.value.delete(targetEventType)+ const record = listeners.value.get(targetEventType)+ if (record && record.channel) {+ try { record.channel.close() } catch { /* ignore */ }}+ listeners.value.delete(targetEventType)}/**- * Send a message to another window+ * Send a message*- * @param {Window} targetWindow - The window to send the message to+ * @param {Window} _targetWindow - Ignored; maintained for API compatibility* @param {Object} options - Options for sending the message* @param {string} options.eventType - The type of message to send (defaults to constructor value)- * @param {string} options.targetOrigin - The origin to send the message to, defaults to '*'- * @param {boolean} options.useMessageChannel - Whether to use MessageChannel for communication- * @param {number} options.timeout - Timeout in ms for the acknowledgment, defaults to 500ms+ * @param {string} options.targetOrigin - Ignored; maintained for API compatibility+ * @param {boolean} options.useMessageChannel - Ignored; maintained for API compatibility+ * @param {number} options.timeout - Timeout in ms for the acknowledgment (best-effort), defaults to 500ms* @param {boolean} options.waitForAcknowledgment - Whether to wait for acknowledgment- * @returns {Promise} - Resolves when acknowledged or after timeout+ * @returns {Promise} - Resolves true if acknowledged, false on timeout, or resolves immediately when not waiting*/- const send = (targetWindow, options = {}) => {+ const send = (_targetWindow, options = {}) => {const {eventType = null,- targetOrigin = '*',- useMessageChannel = true,+ targetOrigin = '*', // unused with BroadcastChannel+ useMessageChannel = true, // unused with BroadcastChanneltimeout = 500,waitForAcknowledgment = true} = options@@ -123,37 +134,61 @@ export const useWindowMessage = (messageType = null) => {}const acknowledgmentName = deriveAcknowledgmentName(targetEventType)-- if (!useMessageChannel) {- // Simple message without MessageChannel- targetWindow.postMessage(targetEventType, targetOrigin)- return Promise.resolve()- } else {- // Using MessageChannel for two-way communication- return new Promise((resolve) => {- // Create a message channel for two-way communication- const channel = new MessageChannel()-- // If we expect an acknowledgment, listen for it- if (waitForAcknowledgment) {- channel.port1.onmessage = (event) => {- if (event.data === acknowledgmentName) {- resolve(true) // Acknowledged- }- }- }-- // Send the message with the port- targetWindow.postMessage(targetEventType, targetOrigin, [channel.port2])-- // Set a timeout as fallback- if (waitForAcknowledgment) {- setTimeout(() => resolve(false), timeout)- } else {- resolve(true)- }- })++ // Helper to post the message+ const postMessage = () => {+ let channel+ try {+ channel = new BroadcastChannel(targetEventType)+ } catch (err) {+ console.error('BroadcastChannel is not supported in this environment', err)+ return null+ }+ channel.postMessage(targetEventType)+ // Close shortly after posting+ setTimeout(() => {+ try { channel.close() } catch { /* ignore */ }+ }, 50)+ return true}++ if (!waitForAcknowledgment) {+ postMessage()+ return Promise.resolve(true)+ }++ // Wait for ack on acknowledgment channel+ return new Promise((resolve) => {+ let ackChannel+ let resolved = false+ try {+ ackChannel = new BroadcastChannel(acknowledgmentName)+ } catch (err) {+ // If BC not supported, fallback to fire-and-forget+ postMessage()+ resolve(false)+ return+ }++ const finalize = (value) => {+ if (resolved) return+ resolved = true+ try { ackChannel.close() } catch { /* ignore */ }+ resolve(value)+ }++ ackChannel.onmessage = (event) => {+ if (event && event.data === acknowledgmentName) {+ finalize(true)+ }+ }++ // Post after listener is attached+ postMessage()++ // Timeout to avoid hanging+ setTimeout(() => finalize(false), timeout)+ })}/**@@ -161,8 +196,8 @@ export const useWindowMessage = (messageType = null) => {* Call this explicitly if needed, though it's automatically called on unmount*/const cleanup = () => {- listeners.value.forEach((handler, type) => {- window.removeEventListener('message', handler)+ listeners.value.forEach((record) => {+ try { record.channel.close() } catch { /* ignore */ }})listeners.value.clear()}diff --git a/client/pages/oauth/[provider]/callback.vue b/client/pages/oauth/[provider]/callback.vueindex a87081a41..427ed22cf 100644--- a/client/pages/oauth/[provider]/callback.vue+++ b/client/pages/oauth/[provider]/callback.vue@@ -37,6 +37,8 @@ const route = useRoute()const loading = ref(true)const authFlow = useAuthFlow()+const loginMessage = useWindowMessage(WindowMessageTypes.LOGIN_COMPLETE)+const providerMessage = useWindowMessage(WindowMessageTypes.OAUTH_PROVIDER_CONNECTED)const handleCallback = async () => {const provider = route.params.provider@@ -61,7 +63,7 @@ const handleCallback = async () => {// Call the OAuth callback endpoint directly to get the raw responseconst response = await authApi.oauth.callback(provider, payloadData)-+// Check if this is an authentication response (has token) or integration response (has provider)if (response.token) {// Authentication flow - user was not logged in@@ -71,9 +73,6 @@ const handleCallback = async () => {// Handle existing user loginif (window.opener) {try {- const loginMessage = useWindowMessage(WindowMessageTypes.LOGIN_COMPLETE)- const providerMessage = useWindowMessage(WindowMessageTypes.OAUTH_PROVIDER_CONNECTED)-await Promise.all([loginMessage.send(window.opener, {waitForAcknowledgment: true,@@ -87,8 +86,7 @@ const handleCallback = async () => {window.close()loading.value = false- } catch (err) {- console.error("Error in social callback:", err)+ } catch {loading.value = false}} else {@@ -103,35 +101,38 @@ const handleCallback = async () => {// Integration flow - user was already logged in, provider was connectedif (window.opener) {try {- const providerMessage = useWindowMessage(WindowMessageTypes.OAUTH_PROVIDER_CONNECTED)-await providerMessage.send(window.opener, {useMessageChannel: false,waitForAcknowledgment: false})- // Auto-close if specified in responseif (response.autoClose) {window.close()} else {useAlert().success(`${response.provider.name} account connected successfully!`)loading.value = false}- } catch (err) {- console.error("Error in integration callback:", err)- useAlert().success(`${response.provider.name} account connected successfully!`)- loading.value = false+ } catch {+ if (!response.autoClose) {+ useAlert().success(`${response.provider.name} account connected successfully!`)+ loading.value = false+ }}} else {- // No opener, show success and redirect- useAlert().success(`${response.provider.name} account connected successfully!`)- router.push({ name: "home" })+ // No opener (tab or cross-context) → rely on useWindowMessage (BC under the hood)+ await providerMessage.send(null, { waitForAcknowledgment: false })+ if (response.autoClose) {+ window.close()+ } else {+ useAlert().success(`${response.provider.name} account connected successfully!`)+ router.push({ name: "home" })+ }}} else {throw new Error("Unexpected response format from OAuth callback")}} catch (error) {- console.error("Social login error:", error)+ console.error("[OAuth Callback] Social login error:", error)useAlert().error(error.response?._data?.message || "Authentication failed")loading.value = false}