0

I use this api to provide google login function for my electron app

https://github.com/googleapis/google-auth-library-nodejs

My access token expires after 3600 seconds

I don’t want my users to log in again after 3600 seconds

How can I make the token refresh automatically?

I try to use the document example code on the my app

But it doesn't seem to work

How can I get a new access_token

I try the code below to get a new access_token

But nothing happens

const { app, BrowserWindow, screen } = require('electron');
const fs = require('fs');
const { google } = require('googleapis'); // auth node js

googleOAuth2Login();

function googleOAuth2Login() {


   const SCOPES = ['https://www.googleapis.com/auth/drive'];
   const TOKEN_PATH = 'token.json';

   fs.readFile('credentials.json', (err, content) => {
       if (err) return console.log('Error loading client secret file:', err);

       authorize(JSON.parse(content), showAccessToken);
   });
 
   function authorize(credentials, callback) {
       const { client_secret, client_id, redirect_uris } = credentials.installed;

       const oAuth2Client = new google.auth.OAuth2(
           client_id,
           client_secret,
           redirect_uris[0]
       );

       // Check if we have previously stored a token.
       fs.readFile(TOKEN_PATH, (err, content) => {
           if (err) return getAccessToken(oAuth2Client, callback);

           oAuth2Client.setCredentials(JSON.parse(content));

           callback(JSON.parse(content))

           oAuth2Client.on('tokens', (tokens) => {
               //this handle not work
               if (tokens.refresh_token) {
                   // store the refresh_token in my database!
                   console.log(tokens.refresh_token);
               }
               console.log(tokens.access_token);
           });

       });
   }
 
   /**
    * This method opens a new window to let users log-in the OAuth provider service,
    * grant permissions to OAuth client service (this application),
    * and returns OAuth code which can be exchanged for the real API access keys.
    * 
    * @param {*} interactionWindow a window in which the user will have interaction with OAuth provider service.
    * @param {*} authPageURL an URL of OAuth provider service, which will ask the user grants permission to us.
    * @returns {Promise<string>}
    */
   function getOAuthCodeByInteraction(interactionWindow, authPageURL) {

       interactionWindow.loadURL(authPageURL, { userAgent: 'Chrome' });

       return new Promise((resolve, reject) => {

           const onclosed = () => {
               reject('Interaction ended intentionally ;(');
           };

           interactionWindow.on('closed', onclosed);
           interactionWindow.on('page-title-updated', (ev) => {

               const url = new URL(ev.sender.getURL());

               // console.log(url.searchParams)

               if (url.searchParams.get('approvalCode')) {

                   console.log('allow')

                   interactionWindow.removeListener('closed', onclosed);
                   interactionWindow.close();

                   return resolve(url.searchParams.get('approvalCode'));
               }
               if ((url.searchParams.get('response') || '').startsWith('error=')) {

                   console.log('reject')
                   interactionWindow.removeListener('closed', onclosed);
                   interactionWindow.close();

                   return reject(url.searchParams.get('response'));
               }
           });
       });

   };

   function executeAuthWindow(authWindow, authUrl) {

       authWindow.setMenu(null);

       authWindow.show();

       return new Promise((resolve, reject) => {

           getOAuthCodeByInteraction(authWindow, authUrl)
               .then((res) => {

                   if (res != 'Interaction ended intentionally ;(') {
                       return resolve(res);
                   }

                   if (res == 'Interaction ended intentionally ;(') {
                       return reject('Fail:Authorization window colose');
                   }

               }).catch((err) => {

                   if (err = 'error=access_denied') {
                       return reject('Fail: error=access_denied');
                   }

               });
       })


   }

   function getAccessToken(oAuth2Client, callback) {

       const authUrl = oAuth2Client.generateAuthUrl({
           access_type: 'offline',
           scope: SCOPES
       });

       const authWindow = new BrowserWindow({
           width: 600,
           height: 800,
           show: false,
           'node-integration': false,
           'web-security': false
       });


       executeAuthWindow(authWindow, authUrl)
           .then((code) => {

               //access_token: and refresh_token:
               oAuth2Client.getToken(code, (err, token) => {

                   if (err) return console.error('Error retrieving access token', err);

                   console.log('getToken')
                   console.log(token)
                   oAuth2Client.setCredentials(token);
                   console.log(oAuth2Client)
                   fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
                       if (err) return console.error(err);
                       console.log('Token stored to', TOKEN_PATH);
                   });

               });

           }).catch((err) => {

               console.log(err)
           })

   }

   // initOAuthClient
   
   function showAccessToken(token) {

       console.log(token)

   }

}

credentials file

{
    "installed": {
        "client_id": "*******17079-*********gjlh6g2nnndhqotn3ij509k.apps.googleusercontent.com",
        "project_id": "quickstart-**********",
        "auth_uri": "https://accounts.google.com/o/oauth2/auth",
        "token_uri": "https://oauth2.googleapis.com/token",
        "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
        "client_secret": "*********dNz3Gceo9F",
        "redirect_uris": [
            "urn:ietf:wg:oauth:2.0:oob",
            "http://localhost"
        ]
    }
}

MING
  • 35
  • 6

0 Answers0