2017-10-14 19:45:35 +08:00
|
|
|
const qs = require('qs'); // eslint-disable-line import/no-extraneous-dependencies
|
|
|
|
const request = require('request');
|
2017-09-24 03:01:50 +08:00
|
|
|
|
|
|
|
function githubToken(clientId, code) {
|
2017-10-14 19:45:35 +08:00
|
|
|
return new Promise((resolve, reject) => {
|
2017-09-24 03:01:50 +08:00
|
|
|
request({
|
|
|
|
method: 'POST',
|
|
|
|
url: 'https://github.com/login/oauth/access_token',
|
|
|
|
qs: {
|
|
|
|
client_id: clientId,
|
|
|
|
client_secret: process.env.GITHUB_SECRET,
|
2017-10-14 19:45:35 +08:00
|
|
|
code,
|
2017-09-24 03:01:50 +08:00
|
|
|
},
|
2017-10-14 19:45:35 +08:00
|
|
|
}, (err, res, body) => {
|
2017-09-24 03:01:50 +08:00
|
|
|
if (err) {
|
|
|
|
reject(err);
|
|
|
|
}
|
2017-10-14 19:45:35 +08:00
|
|
|
const token = qs.parse(body).access_token;
|
2017-09-24 03:01:50 +08:00
|
|
|
if (token) {
|
|
|
|
resolve(token);
|
|
|
|
} else {
|
|
|
|
reject(res.statusCode);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2017-10-14 19:45:35 +08:00
|
|
|
exports.githubToken = (req, res) => {
|
2017-09-27 06:54:26 +08:00
|
|
|
githubToken(req.query.clientId, req.query.code)
|
2017-10-14 19:45:35 +08:00
|
|
|
.then(
|
|
|
|
token => res.send(token),
|
2018-05-06 08:46:33 +08:00
|
|
|
err => res
|
|
|
|
.status(400)
|
|
|
|
.send(err ? err.message || err.toString() : 'bad_code'),
|
|
|
|
);
|
2017-09-24 03:01:50 +08:00
|
|
|
};
|