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