Skip to content

Instantly share code, notes, and snippets.

@WahidinAji
Created October 8, 2024 08:05
Show Gist options
  • Save WahidinAji/3c0bd50b56168a046b980ac5c297e840 to your computer and use it in GitHub Desktop.
Save WahidinAji/3c0bd50b56168a046b980ac5c297e840 to your computer and use it in GitHub Desktop.
ANU
import { NextApiRequest, NextApiResponse } from 'next';
let callbackURL = 'http://localhost:9000/api/v1/auth/google/callback';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { code, state } = req.query;
if (req.method === 'GET') {
try {
let cookie = req.headers.cookie;
const response = await fetch(callbackURL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-Token': 'token',
'Cookie': cookie || '',
},
body: JSON.stringify({ code, state }),
credentials: 'include',
});
if (response.status === 200) {
const data = await response.json();
// Forward the Set-Cookie header from the backend to the client
const cookies = response.headers.get('Set-Cookie');
if (cookies) {
res.setHeader('Set-Cookie', cookies);
}
//remove state-token cookie
// console.log(res.headers);
// res.setHeader('Set-Cookie', 'state-token=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT');
// Redirect to the home page
// res.redirect(302, '/');
res.status(response.status).json({
"message": "Logged in successfully",
"url": data.url,
"fulldata": data
});
} else {
if(response.status === 404) {
const data = await response.json();
res.status(response.status).json(data);
} else {
res.status(response.status).json({
"message": "Authentication failed",
});
}
}
} catch (error) {
console.error('Error in callback:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
} else {
console.log("apa dia bang versi 2");
res.setHeader('Allow', ['GET']);
res.status(405).end(`Method ${req.method} Not Allowed`);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment