Skip to content

Instantly share code, notes, and snippets.

@alex3165
Created April 12, 2019 12:18
Show Gist options
  • Save alex3165/ec9a1f55fa610748119b379539a7853d to your computer and use it in GitHub Desktop.
Save alex3165/ec9a1f55fa610748119b379539a7853d to your computer and use it in GitHub Desktop.
'use strict'
const https = require('https');
const data = JSON.stringify({});
const getOptions = (code) => {
return {
host: 'github.com',
method: 'POST',
path: '/login/oauth/access_token?code=' + code + '&client_id=CLIENT_ID&client_secret=CLIENT_SECRET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
};
exports.handler = (event, context, callback) => {
console.log('Enter lambda with URI: ' + event.Records[0].cf.request.uri);
const request = event.Records[0].cf.request;
if (request.uri !== '/api/github-login') {
console.log('Skip lambda for request URI: ' + request.uri);
callback(null, request);
return;
}
const { code } = event.queryStringParameters;
const options = getOptions(code);
console.log('fetching Github token for code ' + code);
const req = https.request(options, (res) => {
res.setEncoding('utf8');
res.on('data', (chunk) => {
const response = {
body: JSON.parse(chunk),
status: 200
};
callback(null, response);
});
});
req.on('error', (e) => {
console.error('fetching Github token failed with message ' + e.message);
const response = {
status: '500',
statusDescription: 'Error while fetching github token',
headers: {
'cache-control': [{
key: 'Cache-Control',
value: 'max-age=100'
}],
'content-type': [{
key: 'Content-Type',
value: 'application/json'
}],
'content-encoding': [{
key: 'Content-Encoding',
value: 'UTF-8'
}]
},
body: JSON.stringify({
message: e.message
}),
};
callback(e.message, response);
});
req.write(data);
req.end();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment