Spaces:
Build error
Build error
File size: 1,691 Bytes
af5e445 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
export default async function handler(req, res) {
const { code, error } = req.query;
if (error) {
return res.redirect('/?error=google_auth_failed');
}
if (!code) {
return res.redirect('/?error=no_code');
}
try {
// Exchange authorization code for tokens
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: new URLSearchParams({
client_id: process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID,
client_secret: process.env.GOOGLE_CLIENT_SECRET,
code,
grant_type: 'authorization_code',
redirect_uri: `${process.env.NEXTAUTH_URL || 'http://localhost:3000'}/api/auth/callback/google`,
}),
});
const tokenData = await tokenResponse.json();
if (tokenData.error) {
throw new Error(tokenData.error_description);
}
// Get user info
const userResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
headers: {
Authorization: `Bearer ${tokenData.access_token}`,
},
});
const userData = await userResponse.json();
// Here you would typically:
// 1. Check if user exists in your database
// 2. Create or update user record
// 3. Create session/token
// 4. Redirect to dashboard
// For demo purposes, we'll just redirect with user info
const userParam = encodeURIComponent(JSON.stringify(userData));
res.redirect(`/?google_login_success=true&user=${userParam}`);
} catch (error) {
console.error('Google auth error:', error);
res.redirect('/?error=google_auth_failed');
}
} |