forked from conwnet/github1s
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (55 loc) · 1.68 KB
/
Copy pathindex.js
File metadata and controls
62 lines (55 loc) · 1.68 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
/**
* @file github auth callback
* @author netcon
*/
const got = require('got');
const CLIENT_ID = process.env.GITHUB_OAUTH_ID || '';
const CLIENT_SECRET = process.env.GITHUB_OAUTH_SECRET || '';
// allow origins should split by ','
const ALLOWED_ORIGINS = process.env.ALLOWED_ORIGINS || '';
// return the data to the opener window by postMessage API,
// and close current window then
const getResponseHtml = (dataStr) => `
<script>
'${ALLOWED_ORIGINS}'.split(',').forEach(function(allowedOrigin) {
window.opener.postMessage(${dataStr}, allowedOrigin);
});
setTimeout(() => window.close(), 50);
</script>
`;
const MISSING_CODE_ERROR = {
error: 'request_invalid',
error_description: 'Missing code',
};
const UNKNOWN_ERROR = {
error: 'internal_error',
error_description: 'Unknown error',
};
module.exports = async (req, res) => {
const code = req.query.code;
const sendResponseHtml = (status, data) => {
res.status(status);
const responseData = { type: 'authorizing', payload: data };
res.send(getResponseHtml(JSON.stringify(responseData)));
};
if (!code) {
return sendResponseHtml(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 got.post(
'https://github.com/login/oauth/access_token',
{
json: { client_id: CLIENT_ID, client_secret: CLIENT_SECRET, code },
responseType: 'json',
}
);
return sendResponseHtml(response.statusCode, response.body);
} catch (e) {
// the error is responded by GitHub
if (e.response) {
return sendResponseHtml(e.response.statusCode, e.response.body);
}
return sendResponseHtml(500, UNKNOWN_ERROR);
}
};