import { fetch } from "https://esm.town/v/std/fetch";
import process from "node:process";
export async function handleSanguineGithubWebhook(
req: express.Request,
res: express.Response,
) {
console.log("New gh POST req");
console.email(
`you just got a Github Webhook event dog. \n ${JSON.stringify(req)}`,
"Github Webhook on Sanguine extension",
);
const code = req?.query?.code;
if (!code) {
res.status(500).send("No code arrived!");
}
console.log("code: ", code);
try {
const gh_res = await fetch(
`https://github.com/login/oauth/access_token?code=${code}&client_id=${process.env.sanguineGithubClientId}&client_secret=${process.env.sanguineGithubClientSecret}`,
{
method: "POST",
headers: {
"Accept": "*/*",
"Host": "github.com",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Content-Length": "0",
},
},
);
console.log("made it past fetch");
console.log("gh_res: ", gh_res);
if (!gh_res.ok) {
throw new Error(`Failed to fetch`);
}
const gh_res_json = await gh_res.json();
console.log("gs_res_json: ", gh_res_json);
const data = gh_res_json?.data;
console.log("data: ", data);
const accessToken = data?.access_token;
console.log("access_token: ", data);
const userResponse: any = await fetch("https://api.github.com/user", {
headers: {
"Authorization": `Bearer ${accessToken}`,
"User-Agent": "sanguine-extension",
},
});
console.log("userResponse: ", userResponse);
res.json(userResponse?.data);
}
catch (err) {
console.error("Error fetching access token or user data:", err);
res.status(500).send("Authentication failed");
}
}