lib sources restructuring

This commit is contained in:
Roman Krček
2025-07-02 23:56:11 +02:00
parent 878198fabd
commit 81e2e53cc5
19 changed files with 391 additions and 115 deletions

View File

@@ -0,0 +1,57 @@
import { google } from 'googleapis';
import { env } from '$env/dynamic/private';
// Define OAuth scopes for the Google APIs we need to access
export const scopes = [
'https://www.googleapis.com/auth/gmail.send',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/drive.readonly',
'https://www.googleapis.com/auth/spreadsheets.readonly'
];
/**
* Create a new OAuth2 client instance
* @returns Google OAuth2 client
*/
export function getOAuthClient() {
return new google.auth.OAuth2(
env.GOOGLE_CLIENT_ID,
env.GOOGLE_CLIENT_SECRET,
env.GOOGLE_REDIRECT_URI
);
}
/**
* Create a authentication URL for OAuth flow
* @returns Auth URL for Google OAuth
*/
export function createAuthUrl() {
return getOAuthClient().generateAuthUrl({
access_type: 'offline',
prompt: 'consent',
scope: scopes,
redirect_uri: env.GOOGLE_REDIRECT_URI
});
}
/**
* Exchange the authorization code for access and refresh tokens
* @param code - Authorization code from OAuth callback
* @returns Access and refresh tokens
*/
export async function exchangeCodeForTokens(code: string) {
const { tokens } = await getOAuthClient().getToken(code);
if (!tokens.refresh_token) throw new Error('No refresh_token returned');
return tokens;
}
/**
* Get an authenticated client using a refresh token
* @param refreshToken - Refresh token for authentication
* @returns Authenticated OAuth2 client
*/
export function getAuthenticatedClient(refreshToken: string) {
const oauth = getOAuthClient();
oauth.setCredentials({ refresh_token: refreshToken });
return oauth;
}