Skip to content

Instantly share code, notes, and snippets.

@Alric
Forked from ijin/processGitHubHook.js
Created March 24, 2016 21:00
Show Gist options
  • Select an option

  • Save Alric/8a69471f88f1094af06b to your computer and use it in GitHub Desktop.

Select an option

Save Alric/8a69471f88f1094af06b to your computer and use it in GitHub Desktop.

Revisions

  1. @ijin ijin created this gist Aug 11, 2015.
    71 changes: 71 additions & 0 deletions processGitHubHook.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    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();
    }
    }
    });

    };