import getApi from "../system/getAPI"; export async function signInWithProvider(provider: string): Promise { const isMobile = /Mobi|Android/i.test(navigator.userAgent); try { const authUrl = `${getApi()}/oauth/${provider}?` + `provider=${provider}&`; if (isMobile) { // Mobile redirect window.location.href = authUrl; } else { return new Promise(async (resolve, reject) => { try { const maxWidth = 600; const maxHeight = 850; const screenWidth = screen.width; const screenHeight = screen.height; const width = Math.min(screenWidth, maxWidth); const height = Math.min(screenHeight, maxHeight); const left = (screenWidth - width) / 2; const top = (screenHeight - height) / 2; const windowFeatures = `toolbar=no, menubar=no, width=${width}, height=${height}, top=${top}, left=${left}`; const popup = window.open(authUrl, 'OAuth Authentication', windowFeatures); if (!popup) { reject('Unable to open authentication window.'); return; } // Cross-browser compatible popup focus handling popup.focus(); // Polling to check if the popup has been closed const pollTimer = window.setInterval(() => { if (popup.closed) { window.clearInterval(pollTimer); reject('Authentication failed.'); } }, 1000); // Event listener for receiving messages from the popup const messageHandler = (event: any) => { // Validate the origin of the message if (event.origin !== getApi()) { return; } if (event.data.type === 'ultima-oauth') { window.clearInterval(pollTimer); window.removeEventListener('message', messageHandler, false); resolve(event.data.data); } }; window.addEventListener('message', messageHandler, false); } catch (error) { reject(error); } }); } } catch (error) { throw error; } }