Skip to content

Instantly share code, notes, and snippets.

@sunny-g
Last active June 12, 2017 06:37
Show Gist options
  • Save sunny-g/87891ac6a0f29cd43636 to your computer and use it in GitHub Desktop.
Save sunny-g/87891ac6a0f29cd43636 to your computer and use it in GitHub Desktop.
How to create Github OAuth credentials and access tokens with Meteor, without logging-in the user nor using accounts-github
if (Meteor.isClient) {
Template.hello.events({
'click .github': function() {
// initiate the OAuth process:
// ask for the desired permissions
// run the callback after the user authorizes the app
// https://github.com/meteor/meteor/blob/devel/packages/github/github_client.js#L8
Github.requestCredential({
loginStyle: 'popup',
requestPermissions: ['gist']
}, function(tokenOrError) {
if (tokenOrError && tokenOrError instanceof Error) {
// Throw a Meteor error
console.log('error getting the token');
return;
}
// retrieves credentialSecret from localStorage
// https://github.com/meteor/meteor/blob/devel/packages/oauth/oauth_client.js#L152
var credentialSecret = OAuth._retrieveCredentialSecret(tokenOrError);
console.log('credentialToken:', tokenOrError, 'credentialSecret:', credentialSecret);
var accessToken = Meteor.promise('getGithubAccessToken', tokenOrError, credentialSecret);
});
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// sets up the github client service on your server
ServiceConfiguration.configurations.upsert(
{ service: "github" },
{ $set: { clientId: "<YOUR-CLIENT-ID-HERE>", secret: "<YOUR-CLIENT-SECRET-HERE>" } }
);
});
Meteor.methods({
getGithubAccessToken: function(credentialToken, credentialSecret) {
// Github.retrieveCredential wraps OAuth.retrieveCredential, which wraps OAuth._retrievePendingCredential
// From the Meteor docs here: https://github.com/meteor/meteor/blob/devel/packages/oauth/pending_credentials.js#L72
// When an oauth request is made, Meteor receives oauth credentials
// in one browser tab, and temporarily persists them while that
// tab is closed, then retrieves them in the browser tab that
// initiated the credential request.
//
// _pendingCredentials is the storage mechanism used to share the
// credential between the 2 tabs
// After retrieval, they are deleted from the db (unless stored in the User Collection by the developer or by an accounts package)
var credentials = Github.retrieveCredential(credentialToken, credentialSecret);
console.log('accessToken:', credentials.serviceData.accessToken);
return credentials.serviceData.accessToken;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment