· 7 years ago · Sep 15, 2018, 10:38 PM
1 // Load client secrets from a local file.
2 return readFile("credentials.json")
3 .then(async content => {
4 const token = await authorize(JSON.parse(content));
5 return await parseAttachment(token);
6 })
7 .catch(err => {
8 return console.log("Error loading client secret file:", err);
9 })
10
11 /**
12 * Create an OAuth2 client with the given credentials, and then execute the
13 * given callback function.
14 * @param {Object} credentials The authorization client credentials.
15 * @param {function} callback The callback to call with the authorized client.
16 */
17 async function authorize(credentials) {
18 const { client_secret, client_id, redirect_uris } = credentials.installed;
19 const oAuth2Client = new google.auth.OAuth2(
20 client_id, client_secret, redirect_uris[0]
21 );
22
23 // Check if we have previously stored a token.
24 try {
25 const oAuthToken = await readFile(TOKEN_PATH);
26 oAuth2Client.setCredentials(JSON.parse(oAuthToken));
27 } catch (err) {
28 await getNewToken(oAuth2Client);
29 }
30 return oAuth2Client;
31 }
32
33 /**
34 * Get and store new token after prompting for user authorization, and then
35 * execute the given callback with the authorized OAuth2 client.
36 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
37 * @param {getEventsCallback} callback The callback for the authorized client.
38 */
39 function getNewToken(oAuth2Client) {
40 const authUrl = oAuth2Client.generateAuthUrl({
41 access_type: 'offline',
42 scope: SCOPES,
43 });
44 console.log('Authorize this app by visiting this url:', authUrl);
45 const rl = readline.default.createInterface({
46 input: process.stdin,
47 output: process.stdout,
48 });
49
50 return rl.questionAsync('Enter the code from that page here: ')
51 .then(code => {
52 return oAuth2Client.getToken(code);
53 })
54 .then(tokenData => {
55 const token = tokenData.tokens;
56 oAuth2Client.setCredentials(token);
57 // Store the token to disk for later program executions
58 writeFile(TOKEN_PATH, JSON.stringify(token))
59 console.log("Token stored to", TOKEN_PATH);
60 return oAuth2Client;
61 })
62 .catch(err => {
63 return console.error(err);
64 })
65 }