Repository navigation
Expand file tree
/
Copy pathgithub-auth-callback.ts
More file actions
69 lines (62 loc) · 2.18 KB
/
Copy pathgithub-auth-callback.ts
File metadata and controls
69 lines (62 loc) · 2.18 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
/**
* @file github auth callback
* @author netcon
*/
const createResponseHtml = (text: string, script: string) => `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Connect to GitHub</title>
</head>
<body>
<h1>${text}</h1>
<script>${script}</script>
</body>
</html>
`;
// return the data to the opener window by postMessage API,
// and close current window if successfully connected
const createAuthorizeResultHtml = (data: Record<any, any>, origins: string) => {
const errorText = 'Failed! You can close this window and retry.';
const successText = 'Connected! You can now close this window.';
const resultStr = `{ type: 'authorizing', payload: ${JSON.stringify(data)} }`;
const script = `
'${origins}'.split(',').forEach(function(allowedOrigin) {
window.opener.postMessage(${resultStr}, allowedOrigin);
});
${data.error ? '' : 'setTimeout(() => window.close(), 50);'}`;
return createResponseHtml(data.error ? errorText : successText, script);
};
const MISSING_CODE_ERROR = {
error: 'request_invalid',
error_description: 'Missing code',
};
const UNKNOWN_ERROR = {
error: 'internal_error',
error_description: 'Unknown error',
};
export const onRequest: PagesFunction<{
GITHUB_OAUTH_ID: string;
GITHUB_OAUTH_SECRET: string;
GITHUB1S_ALLOWED_ORIGINS: string;
}> = async ({ request, env }) => {
const code = new URL(request.url).searchParams.get('code');
const createResponse = (status, data) => {
const body = createAuthorizeResultHtml(data, env.GITHUB1S_ALLOWED_ORIGINS);
return new Response(body, { status, headers: { 'content-type': 'text/html' } });
};
if (!code) {
return createResponse(401, MISSING_CODE_ERROR);
}
try {
// https://docs.github.com/en/developers/apps/authorizing-oauth-apps#2-users-are-redirected-back-to-your-site-by-github
const response = await fetch('https://github.com/login/oauth/access_token', {
method: 'POST',
body: JSON.stringify({ client_id: env.GITHUB_OAUTH_ID, client_secret: env.GITHUB_OAUTH_SECRET, code }),
headers: { accept: 'application/json', 'content-type': 'application/json' },
});
return response.json().then((result) => createResponse(response.status, result));
} catch (e) {
return createResponse(500, UNKNOWN_ERROR);
}
};