All files / auth github.js

50% Statements 47/94
83.33% Branches 5/6
50% Functions 2/4
50% Lines 47/94

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 951x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 5x 5x 5x 1x 1x             1x 1x                                                                     1x 1x 4x 4x 4x               4x 4x 4x 4x 4x 4x 1x 1x  
var bag = require('bagofrequest');
var github = require('@octokit/rest');
var url = require('url');
var dotfile = require('dotfile')('repomanrc');
var BluePromise = require('bluebird');
 
/**
 * Configuration generator for remote GitHub repositories.
 *
 * @param {String} user: GitHub username
 * @param {String} pass: GitHub password
 * @class
 */
function GithubAuth() {
  var opts = {
    version: '3.0.0',
    timeout: 30000
  };
 
  var proxy = bag.proxy();
  if (proxy) {
    proxy = url.parse(proxy);
    opts.proxy = {
      host: proxy.hostname,
      port: proxy.port
    };
  }
 
  this.gh = new github(opts);
}
 
GithubAuth.prototype.authBasic = function(user, pass) {
  return this.gh.authenticate({
    type: 'basic',
    username: user,
    password: pass
  });
};
 
GithubAuth.prototype.fetchAndStoreAuthToken = function(optionalTwoFactor) {
  var self = this;
  return new BluePromise(function(s, f) {
    var headers = {};
    if (optionalTwoFactor) {
      headers['X-GitHub-OTP'] = optionalTwoFactor;
    }
    self.gh.authorization.create(
      {
        scopes: ['user', 'public_repo', 'repo', 'repo:status', 'gist'],
        note: 'read repos for repoman4',
        headers: headers
      },
      function(err, res) {
        if (res && res.data && res.data.token) {
          self.ghToken = res.data.token;
          console.log('got Github auth token');

          dotfile.exists(function() {
            dotfile.write({ githubAuthToken: self.ghToken }, function() {
              dotfile.read(function(err, disk) {
                console.log('saved Github auth');
                console.log(disk);
                s();
              });
            });
          });
        } else if (err) {
          console.log(err);
          f(err);
        }
      }
    );
  });
};
 
GithubAuth.prototype.readAuthToken = function() {
  return new BluePromise(function(s, f) {
    dotfile.exists(function(yesno) {
      if (yesno) {
        dotfile.read(function(err, disk) {
          if (disk.githubAuthToken) {
            s(disk.githubAuthToken);
          } else {
            f(new Error('no auth token in dotfile'));
          }
        });
      } else {
        f(new Error('no dotfile'));
      }
    });
  });
};
 
module.exports = GithubAuth;