Created
August 9, 2018 04:34
-
-
Save Tolsee/445cb0c8d0b5c3ed89883010b77da9e5 to your computer and use it in GitHub Desktop.
Authenticate with google calendar and store token for next use.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const gEvent = require('vorpal')(); | |
const {google} = require('googleapis'); | |
const opn = require('opn'); | |
const utils = require('./utils'); | |
const CLIENT_ID = 'GOOGLE_CLIENT_ID'; | |
const CLIENT_SECRET = 'GOOGLE_CLIENT_SECRET'; | |
const REDIRECT_URL = 'urn:ietf:wg:oauth:2.0:oob'; | |
const oauth2Client = new google.auth.OAuth2( | |
CLIENT_ID, | |
CLIENT_SECRET, | |
REDIRECT_URL | |
); | |
// generate a url that asks permissions for Google Calendar scopes | |
const scopes = [ | |
'https://www.googleapis.com/auth/calendar', | |
'https://www.googleapis.com/auth/calendar.readonly' | |
]; | |
let url; | |
// set credentials if already present else create a url to connect | |
if (utils.checkAuth()) { | |
oauth2Client.setCredentials(utils.readConfig()); | |
} else { | |
url = oauth2Client.generateAuthUrl({ | |
access_type: 'offline', | |
scope: scopes | |
}); | |
} | |
gEvent | |
.command('connect') | |
.description('Connect to your google account') | |
.action(function (args, callback) { | |
if (utils.checkAuth()) { | |
this.log('You are already connected.'); | |
return callback(); | |
} | |
opn(url); | |
callback(); | |
}); | |
gEvent | |
.command('authorize <code>') | |
.description('Authorize your account with token') | |
.action(async function (args, callback) { | |
if (utils.checkAuth()) { | |
this.log('You are already connected.'); | |
return callback(); | |
} | |
const {tokens} = await oauth2Client.getToken(args.code); | |
oauth2Client.setCredentials(tokens); | |
// Store tokens for next use | |
utils.writeConfig(tokens); | |
callback(); | |
}); | |
gEvent | |
.command('disconnect') | |
.description('Disconnect the current google account') | |
.action(async function (args, callback) { | |
// Simply erase the access_token and refresh_token | |
utils.writeConfig({}); | |
callback(); | |
}); | |
gEvent | |
.delimiter('gevent $') | |
.show(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment