Refactor authentication flow in GraphApiClient to improve token retrieval and logging

- Removed inline comments for clarity and added console logs for better debugging during the OAuth process.
- Updated the handling of the redirect and navigation events to streamline access token extraction from cookies.
- Implemented a new method to manage callback handling, ensuring proper closure of the authentication window and error handling.
- Enhanced logging for navigation and redirect events to provide better visibility into the authentication process.
This commit is contained in:
Tiger Ren 2025-01-09 01:19:31 +08:00
parent 59b8367275
commit 7c6e46c77f
1 changed files with 42 additions and 21 deletions

View File

@ -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'));
});
});