74 lines
2.3 KiB
TypeScript
74 lines
2.3 KiB
TypeScript
function renderBody(status: string, content: any) {
|
|
const html = `
|
|
<script>
|
|
const receiveMessage = (message) => {
|
|
window.opener.postMessage(
|
|
'authorization:github:${status}:${JSON.stringify(content)}',
|
|
message.origin
|
|
);
|
|
window.removeEventListener("message", receiveMessage, false);
|
|
}
|
|
window.addEventListener("message", receiveMessage, false);
|
|
window.opener.postMessage("authorizing:github", "*");
|
|
</script>
|
|
`;
|
|
const blob = new Blob([html]);
|
|
return blob;
|
|
}
|
|
|
|
export async function onRequest(context: any) {
|
|
const {
|
|
request, // same as existing Worker API
|
|
env, // same as existing Worker API
|
|
} = context;
|
|
|
|
const client_id = env.GITHUB_CLIENT_ID;
|
|
const client_secret = env.GITHUB_CLIENT_SECRET;
|
|
|
|
try {
|
|
const url = new URL(request.url);
|
|
const code = url.searchParams.get('code');
|
|
const response = await fetch(
|
|
'https://github.com/login/oauth/access_token',
|
|
{
|
|
method: 'POST',
|
|
headers: {
|
|
'content-type': 'application/json',
|
|
'user-agent': 'cloudflare-functions-github-oauth-login-demo',
|
|
'accept': 'application/json',
|
|
},
|
|
body: JSON.stringify({ client_id, client_secret, code }),
|
|
},
|
|
);
|
|
const result = (await response.json()) as any;
|
|
if (result.error) {
|
|
return new Response(renderBody('error', result), {
|
|
headers: {
|
|
'content-type': 'text/html;charset=UTF-8',
|
|
},
|
|
status: 401
|
|
});
|
|
}
|
|
const token = result.access_token;
|
|
const provider = 'github';
|
|
const responseBody = renderBody('success', {
|
|
token,
|
|
provider,
|
|
});
|
|
return new Response(responseBody, {
|
|
headers: {
|
|
'content-type': 'text/html;charset=UTF-8',
|
|
},
|
|
status: 200
|
|
});
|
|
|
|
} catch (error: any) {
|
|
console.error(error);
|
|
return new Response(error.message, {
|
|
headers: {
|
|
'content-type': 'text/html;charset=UTF-8',
|
|
},
|
|
status: 500,
|
|
});
|
|
}
|
|
} |