Stackedit/server/github.js

37 lines
894 B
JavaScript
Raw Permalink Normal View History

2017-10-14 11:45:35 +00:00
const qs = require('qs'); // eslint-disable-line import/no-extraneous-dependencies
const request = require('request');
2017-09-23 19:01:50 +00:00
function githubToken(clientId, code) {
2017-10-14 11:45:35 +00:00
return new Promise((resolve, reject) => {
2017-09-23 19:01:50 +00: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 11:45:35 +00:00
code,
2017-09-23 19:01:50 +00:00
},
2017-10-14 11:45:35 +00:00
}, (err, res, body) => {
2017-09-23 19:01:50 +00:00
if (err) {
reject(err);
}
2017-10-14 11:45:35 +00:00
const token = qs.parse(body).access_token;
2017-09-23 19:01:50 +00:00
if (token) {
resolve(token);
} else {
reject(res.statusCode);
}
});
});
}
2017-10-14 11:45:35 +00:00
exports.githubToken = (req, res) => {
2017-09-26 22:54:26 +00:00
githubToken(req.query.clientId, req.query.code)
2017-10-14 11:45:35 +00:00
.then(
token => res.send(token),
2018-05-06 00:46:33 +00:00
err => res
.status(400)
.send(err ? err.message || err.toString() : 'bad_code'),
);
2017-09-23 19:01:50 +00:00
};