diff --git a/renderer/graphApi.js b/renderer/graphApi.js index d3c181a..4e8960a 100644 --- a/renderer/graphApi.js +++ b/renderer/graphApi.js @@ -12,7 +12,6 @@ class GraphApiClient { async getAccessToken() { return new Promise((resolve, reject) => { - // Create the auth window const authWindow = new BrowserWindow({ width: 800, height: 600, @@ -27,34 +26,56 @@ class GraphApiClient { `client_id=${this.clientId}` + `&nonce=uv.${uuidv4()}` + `&response_mode=form_post` + - `&scope=${this.scopes}` + + `&scope=${encodeURIComponent(this.scopes)}` + `&response_type=code` + `&redirect_uri=${encodeURIComponent(this.redirectUrl)}`; - - // Load the OAuth URL + console.log('Loading auth URL:', authUrl); authWindow.loadURL(authUrl); - // Handle the redirect - authWindow.webContents.on('will-redirect', (event, url) => { - const parsedUrl = new URL(url); - const hash = parsedUrl.hash.substring(1); // Remove the # symbol - - if (hash.includes('access_token=')) { - const params = new URLSearchParams(hash); - const token = params.get('access_token'); - authWindow.close(); - resolve(token); - } else if (hash.includes('error=')) { - const params = new URLSearchParams(hash); - const error = params.get('error_description'); - authWindow.close(); - reject(new Error(error)); - } + // Handle the navigation events + authWindow.webContents.on('will-navigate', (event, url) => { + console.log('Navigation detected:', url); + handleCallback(url); }); - // Handle close + authWindow.webContents.on('will-redirect', (event, url) => { + console.log('Redirect detected:', url); + handleCallback(url); + }); + + const handleCallback = async (callbackUrl) => { + // Check if this is our redirect URI + if (callbackUrl.startsWith(this.redirectUrl)) { + console.log('Redirect URI matched, getting cookies...'); + + try { + // Get all cookies + const cookies = await authWindow.webContents.session.cookies.get({}); + console.log('Found cookies:', cookies.length); + + // Find the access token + const accessToken = cookies.find( + cookie => cookie.name === 'AccessToken-OneDrive.ReadWrite' + ); + + if (accessToken) { + console.log('Found access token in cookies'); + authWindow.close(); + resolve(accessToken.value); + } else { + console.log('Access token not found in cookies, waiting...'); + } + } catch (error) { + console.error('Error getting cookies:', error); + reject(error); + } + } + }; + + // Handle window closing authWindow.on('closed', () => { + console.log('Auth window closed'); reject(new Error('Authentication window was closed')); }); });