2025-06-30 20:33:53 +08:00

80 lines
2.8 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server';
// Prevent static rendering of this route
export const dynamic = 'force-dynamic';
/**
* Handle Google OAuth callback
* In a real app, this would:
* 1. Exchange the authorization code for tokens
* 2. Verify the token and get user info from Google
* 3. Create or update the user in your database
* 4. Set session/cookies
* 5. Redirect to the app
*/
export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const code = searchParams.get('code');
const error = searchParams.get('error');
const state = searchParams.get('state');
console.log('Google OAuth callback received', {
hasCode: !!code,
error: error || 'none',
hasState: !!state,
url: request.url
});
// Handle errors from Google
if (error) {
console.error('Google OAuth error:', error);
return NextResponse.redirect(new URL(`/login?error=${encodeURIComponent(error)}`, request.url));
}
if (!code) {
console.error('No authorization code received from Google');
return NextResponse.redirect(new URL('/login?error=no_code', request.url));
}
// The state parameter validation will happen client-side
// since we're storing the original state in sessionStorage
// We'll add the state to the redirect URL so the client can validate it
try {
console.log('Processing OAuth callback with code', code.substring(0, 5) + '...');
// In a real app, you would exchange the code for tokens
// and validate the tokens here
// For this demo, we'll just simulate a successful login
// by redirecting with a mock session token
const redirectUrl = new URL('/', request.url);
// Mock user data that would normally come from Google
const mockUser = {
id: 'google-123456',
name: 'Google User',
email: 'user@gmail.com',
picture: 'https://i.pravatar.cc/150',
};
// In a real app, you would set cookies or session data here
// Simulate setting a session by adding a URL parameter
// In a real app, don't pass sensitive data in URL parameters
redirectUrl.searchParams.set('session', 'demo-session-token');
redirectUrl.searchParams.set('user', encodeURIComponent(JSON.stringify(mockUser)));
// Pass the state back to the client for validation
if (state) {
redirectUrl.searchParams.set('state', state);
}
console.log('Redirecting to:', redirectUrl.toString());
return NextResponse.redirect(redirectUrl);
} catch (error) {
console.error('Failed to process Google authentication:', error);
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
return NextResponse.redirect(new URL(`/login?error=auth_failed&details=${encodeURIComponent(errorMessage)}`, request.url));
}
}