-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathindex.js
72 lines (63 loc) · 2.17 KB
/
index.js
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
70
71
72
require('dotenv').config()
const querystring = require('querystring')
const axios = require('axios')
const { router, get } = require('microrouter');
const redirect = require('micro-redirect');
const uid = require('uid-promise');
const githubUrl = process.env.GH_HOST || 'github.com'
const states = [];
const redirectWithQueryString = (res, data) => {
const location = `${process.env.REDIRECT_URL}?${querystring.stringify(data)}`
redirect(res, 302, location)
}
const login = async (req, res) => {
const state = await uid(20);
states.push(state);
const { scope, allow_signup } = req.query;
const query = {
client_id: process.env.GH_CLIENT_ID,
state: state
};
if (scope) query.scope = scope;
if (allow_signup !== undefined) query.allow_signup = allow_signup;
redirect(res, 302, `https://${githubUrl}/login/oauth/authorize?${querystring.stringify(query)}`);
};
const callback = async (req, res) => {
res.setHeader('Content-Type', 'text/html')
const { code, state } = req.query
if (!code && !state) {
redirectWithQueryString(res, { error: 'Provide code and state query param' })
} else if (!states.includes(state)) {
redirectWithQueryString(res, { error: 'Unknown state' })
} else {
states.splice(states.indexOf(state), 1);
try {
const { status, data } = await axios({
method: 'POST',
url: `https://${githubUrl}/login/oauth/access_token`,
responseType: 'json',
data: {
client_id: process.env.GH_CLIENT_ID,
client_secret: process.env.GH_CLIENT_SECRET,
code
}
})
if (status === 200) {
const qs = querystring.parse(data)
if (qs.error) {
redirectWithQueryString(res, { error: qs.error_description })
} else {
redirectWithQueryString(res, { access_token: qs.access_token })
}
} else {
redirectWithQueryString(res, { error: 'GitHub server error.' })
}
} catch (err) {
redirectWithQueryString(res, { error: 'Please provide GH_CLIENT_ID and GH_CLIENT_SECRET as environment variables. (or GitHub might be down)' })
}
}
}
module.exports = router(
get('/login', login),
get('/callback', callback)
);