Skip to content

Instantly share code, notes, and snippets.

@aklkv
Forked from ijin/processGitHubHook.js
Last active September 6, 2015 06:49
Show Gist options
  • Save aklkv/8ccce50f1800dd2eb7a3 to your computer and use it in GitHub Desktop.
Save aklkv/8ccce50f1800dd2eb7a3 to your computer and use it in GitHub Desktop.
aws lambda function to process github hook from sns, add user to team, and notify by slack.
var aws = require('aws-sdk');
var kms = new aws.KMS({ region: 'us-east-1' });
var lambda = new aws.Lambda({region: 'ap-northeast-1'});
var encrypted_token = 'CiD0R0tv46w7LNpO0GlZpLfZk2O0Oy66IF83rG6olDY7yBKwAQEBAgB49EdL\nb+OsOyzaTtBpWaS32ZNjtDsuuiBfN6xuqJQ2O8gAAACHMIGEBgkqhkiG9w0B\nBwagdzB1AgEAMHAGCSqGSIb3DQEHATAeBglghkgBZQMEAS4wEQQMsDOYHRzB\nN/5q/XCTAgEQgEOnHbGFykvpf06OQ1uQG9P5VjooLu8oSynMp9Cqt5SvaPUC\nKpHkPnnew8nKYhDIcxyLYd/A3vYsHZGWZ3FwN7kx0tIx\n';
var team_id = 1234567;
var valid_comment = 'join';
//console.log('Loading function');
exports.handler = function(event, context) {
console.log('Received event:', JSON.stringify(event, null, 2));
var message = JSON.parse(event.Records[0].Sns.Message);
//console.log('From SNS:', message);
var comment = message.comment.body;
var user = message.comment.user.login;
var icon = message.comment.user.avatar_url;
console.log('user: ' + user);
console.log('comment: ' + comment);
var p = {CiphertextBlob: new Buffer(encrypted_token, 'base64')};
kms.decrypt(p, function(err, data) {
if (err) context.fail(err);
else {
var github_token = data.Plaintext.toString();
//console.log('token: ' + github_token);
var http = require('https');
var options = {
host: 'api.github.com',
port: 443,
path: '/teams/' + team_id + '/memberships/' + user,
headers: {'Authorization': 'token ' + github_token, 'User-Agent': 'ijin'},
method: 'PUT'
};
callback = function(response) {
var rsp = '';
var msg = '';
var status = response.statusCode;
console.log('status code: ' + status);
response.on('data', function (chunk) { rsp += chunk; });
response.on('end', function () {
console.log('response: ' + rsp);
if (status == 200){
msg = 'Added to the team';
console.log(msg);
var payload = { username: user, icon_url: icon, text: msg }
lambda.invoke({FunctionName: 'slack', Payload: JSON.stringify(payload)}, function(err, data) {
if (err) console.log(err, err.stack);
else context.succeed(msg);
});
} else {
msg = 'Failed to add user to the team';
console.log(msg);
context.fail(msg);
}
});
}
if (valid_comment.indexOf(comment) < 0) context.fail('invalid comment');
else {
var req = http.request(options, callback);
req.end();
}
}
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment