简体   繁体   中英

(nodegit) How to read/write from/to private Github repo using a token

I copied some code from the net and got it working to clone and push to one of my own repos on github. Using the same code I tried to do the same with a repo now owned by me but by an organisation that I am part of and that I have write access to. This fails with a 403.

Here's the code I use.

GithubClient.js

var fs = require('fs');
var NodeGit = require('nodegit');
var config = require('./github-config.js');


var cloneOpts = {
  callbacks: {
    certificateCheck: () => {
      return 1;
    },
    credentials: function(url, username) {
      console.log('creds for' + username);
      return nodegit.Cred.userpassPlaintextNew(config.token, "x-oauth-basic");
    }
  }
};

cloneOpts.fetchOpts = {
  callbacks: cloneOpts.callbacks
};

class GitClient {

  static clone(options) {
    cloneOpts.checkoutBranch = options.branch;
    return NodeGit.Clone(options.remote, options.local, cloneOpts)
      .catch(err => console.log(err));
  }

  static addAndCommit(repo, filesArray, msg) {
    return repo.createCommitOnHead(
      filesArray,
      NodeGit.Signature.create(config.realname, config.email, new Date().getTime(), 0),
      NodeGit.Signature.create(config.realname, config.email, new Date().getTime(), 0),
      msg
    );
  }

  static push(repo, repoName, remoteName, refs) {
    return repo.getRemote(remoteName || 'origin')
      .then(remote => {
        return remote.push(
          refs || [`refs/heads/${repoName || 'main'}:refs/heads/${repoName || 'main'}`],
          cloneOpts
        ).then(function() {
          console.log('success', arguments);
        });
      });
  }
}

module.exports = GitClient;

GithubClientRunner.js

var fs = require('fs');
var GitClient = require('./GithubClient.js');
var config = require('./github-config.js');

let repo;
console.log('starting clone');
return GitClient.clone({
    branch: config.branch,
    remote: config.remote,
    local: config.local
  }).then(r => {
    repo = r;
    let contents = new Date().getTime() + ' please ignore - will remove soon';
    console.log('got repo, writing contents:', contents);
    fs.writeFileSync(config.local + '/myTemporaryTestFile', contents);
    // add the file
    return GitClient.addAndCommit(repo, ['myTemporaryTestFile'], 'Test Commit not breaking anything');
  }).then(() => {
    console.log('commit done, pushing');
    return GitClient.push(repo, config.branch);
  })
  .then(() => {
    console.log('done');
    process.exit(0);
  })
  .catch(err => {
    console.error('uncaught!', err);
    process.exit(1);
  });

This is the config for my own repo (working):

const config = {
  branch: 'main',
  remote: 'https://___MY_GITHUB_TOKEN___:x-oauth-basic@github.com/MyGitHubUserName/myTestRepo.git',
  local: './.gitcache/myTestRepo.io',
  username: 'MyGitHubUserName',
  realname: 'My Name',
  email: 'me@email.com',
  token: '___MY_GITHUB_TOKEN___'
};
module.exports = config;

The outcome is as follows:

starting clone
got repo, writing contents: 1612971904692 please ignore - will remove soon
commit done, pushing
success [Arguments] { '0': undefined }
done

And now this is the config for the organisations repo (not working):

const config = {
  branch: 'main',
  remote: 'https://___MY_GITHUB_TOKEN___:x-oauth-basic@github.com/theOrganisationIAmAMemberOf/someOtherRepo.git',
  local: './.gitcache/someOtherRepo.io',
  username: 'MyGitHubUserName',
  realname: 'My Name',
  email: 'me@email.com',
  token: '___MY_GITHUB_TOKEN___'
};
module.exports = config;

The outcome now is:

starting clone
[Error: unexpected HTTP status code: 403] {
  errno: -1,
  errorFunction: 'Clone.clone'
}

How can I make the code work with both types of repos?

Thank you!

I found the mistake myself. The code is working properly as expected. However I forgot the enable my token for the organisation. As soon as I did that it all worked just fine.

Pro tip: if you encounter an authentication problem and the error message doesn't help try to achieve the same thing using the command line git client. Error messages there will be much more informative.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM