auth.ts•2.63 kB
import { google } from 'googleapis';
import { OAuth2Client } from 'google-auth-library';
import * as fs from 'fs';
import * as path from 'path';
export interface GoogleSlidesConfig {
clientId: string;
clientSecret: string;
redirectUri: string;
}
export class GoogleSlidesAuth {
private oauth2Client: OAuth2Client;
private slides: any;
constructor(config: GoogleSlidesConfig) {
this.oauth2Client = new google.auth.OAuth2(
config.clientId,
config.clientSecret,
config.redirectUri
);
// Initialize the Slides API
this.slides = google.slides({ version: 'v1', auth: this.oauth2Client });
}
/**
* Generate the authorization URL for OAuth2 flow
*/
getAuthUrl(): string {
const scopes = [
'https://www.googleapis.com/auth/presentations',
'https://www.googleapis.com/auth/drive.file'
];
return this.oauth2Client.generateAuthUrl({
access_type: 'offline',
scope: scopes,
});
}
/**
* Exchange authorization code for tokens
*/
async getTokens(code: string): Promise<void> {
const { tokens } = await this.oauth2Client.getToken(code);
this.oauth2Client.setCredentials(tokens);
// Save tokens for future use
await this.saveTokens(tokens);
}
/**
* Load saved tokens from file
*/
async loadTokens(): Promise<boolean> {
const tokenPath = path.join(process.cwd(), 'token.json');
try {
if (fs.existsSync(tokenPath)) {
const tokens = JSON.parse(fs.readFileSync(tokenPath, 'utf8'));
this.oauth2Client.setCredentials(tokens);
return true;
}
} catch (error) {
console.error('Error loading tokens:', error);
}
return false;
}
/**
* Save tokens to file
*/
private async saveTokens(tokens: any): Promise<void> {
const tokenPath = path.join(process.cwd(), 'token.json');
fs.writeFileSync(tokenPath, JSON.stringify(tokens, null, 2));
}
/**
* Check if the client is authenticated
*/
isAuthenticated(): boolean {
return !!this.oauth2Client.credentials.access_token;
}
/**
* Get the Google Slides API client
*/
getSlidesClient() {
if (!this.isAuthenticated()) {
throw new Error('Not authenticated. Please authenticate first.');
}
return this.slides;
}
/**
* Refresh access token if needed
*/
async refreshTokenIfNeeded(): Promise<void> {
try {
await this.oauth2Client.getAccessToken();
} catch (error) {
console.error('Error refreshing token:', error);
throw new Error('Authentication expired. Please re-authenticate.');
}
}
}