import { redirect } from '@sveltejs/kit'; import type { RequestHandler } from './$types'; import { googleAuthServer } from '$lib/google/server.ts'; export const GET: RequestHandler = async ({ url }) => { try { const code = url.searchParams.get('code'); const error = url.searchParams.get('error'); if (error) { console.error('Google OAuth error:', error); throw redirect(302, '/private/events?error=google_auth_denied'); } if (!code) { throw redirect(302, '/private/events?error=missing_auth_code'); } // Exchange code for tokens const oauth = googleAuthServer.getOAuthClient(); const { tokens } = await oauth.getToken(code); if (!tokens.refresh_token || !tokens.access_token) { throw redirect(302, '/private/events?error=incomplete_tokens'); } // Get user info to retrieve email let userEmail = ''; try { oauth.setCredentials(tokens); const { google } = await import('googleapis'); const oauth2 = google.oauth2({ version: 'v2', auth: oauth }); const userInfo = await oauth2.userinfo.get(); userEmail = userInfo.data.email ?? ''; } catch (emailError) { console.error('Error fetching user email:', emailError); // Continue without email - it's not critical for the auth flow } // Create a success page with tokens that closes the popup and communicates with parent const html = ` Google Authentication Success
✓ Authentication successful!
Closing window...
`; return new Response(html, { headers: { 'Content-Type': 'text/html' } }); } catch (error) { console.error('Error handling Google OAuth callback:', error); throw redirect(302, '/private/events?error=google_auth_failed'); } };