import fs = require ( 'fs' ) ; import readline = require ( 'readline' ) ; import { google } from 'googleapis' ; import { OAuth2Client } from 'google-auth-library' ; const SCOPE = 'https://www.googleapis.com/auth/drive' ; const TOKEN_PATH = './credentials.json' ; param { function } callback export function call ( callback ) { fs . readFile ( './client_secret.json' , 'utf8' , ( err , content ) => { if ( err ) { console . log ( 'Error loading client secret file:' , err . message ) ; callback ( err . message , null ) ; } else { authorize ( JSON . parse ( content ) , callback ) ; } } ) ; } param { Object } credentials param { function } callback function authorize ( credentials , callback ) { const clientSecret = credentials . installed . client_secret ; const clientId = credentials . installed . client_id ; const redirectUris = credentials . installed . redirect_uris ; const oAuth2Client = new google . auth . OAuth2 ( clientId , clientSecret , redirectUris [ 0 ] ) ; fs . readFile ( TOKEN_PATH , 'utf8' , ( err , token ) => { if ( err ) return getAccessToken ( oAuth2Client , callback ) ; oAuth2Client . setCredentials ( JSON . parse ( token ) ) ; callback ( null , oAuth2Client ) ; } ) ; } param { google . auth . OAuth2 } oAuth2Client param { getEventsCallback } callback function getAccessToken ( oAuth2Client , callback ) { const authUrl = oAuth2Client . generateAuthUrl ( { access_type : 'offline' , scope : SCOPE } ) ; console . log ( 'Authorize this app by visiting this url:' , authUrl ) ; const rl = readline . createInterface ( { input : process . stdin , output : process . stdout } ) ; rl . question ( 'Enter the code from that page here: ' , ( code ) => { rl . close ( ) ; oAuth2Client . getToken ( code , ( err , token ) => { if ( err ) return callback ( err . message , null ) ; oAuth2Client . setCredentials ( token ) ; fs . writeFile ( TOKEN_PATH , JSON . stringify ( token ) , ( err ) => { if ( err ) console . error ( err ) ; console . log ( 'Token stored to' , TOKEN_PATH ) ; } ) ; callback ( null , oAuth2Client ) ; } ) ; } ) ; }