Access to Google Drive through Service Account : Error: Login Required

Viewed 621
const {google} = require('googleapis');
let drive = google.drive('v3');

exports.handler = async (req, res) => {
    res.set('Access-Control-Allow-Origin', '*')
      .set('Access-Control-Allow-Methods', 'POST')
    .status(200);
  var privatekey 
  var jwtClient 
  await global.admin.database().ref(`g_drive_token/OfficServiceAccount`).once('value').then((doc)=> {
    privatekey = doc.val()
    jwtClient = new google.auth.JWT(
      privatekey.client_email,
      null,
      privatekey.private_key,
      ['https://www.googleapis.com/auth/drive.file'],
      null);
      console.log(JSON.stringify(jwtClient))   
      authWithServicePrivateKey(jwtClient)
      return "null"
    }) .catch((error)=> {            
    console.log('Error fetching user data:+', error);
      return "null"
  }) 


function authWithServicePrivateKey(jwtClient){
  //authenticate request
jwtClient.authorize(function (err, tokens) {
    if (err) {
      console.log("Could not connect***!"+err);
      return;
    } else {
      console.log("Successfully connected!");
      console.log('token******'+JSON.stringify(tokens))
      listFolderInGoogleDrive()
      CreateFolderInGoogleDrive()
    }
   });
}


//Google Drive API
function listFolderInGoogleDrive() {
    console.log('listFolderInGoogleDrive() was called')
    drive.files.list({
        auth: jwtClient,
        pageSize: 10,
        fields: 'nextPageToken, files(id, name)',
      }, (err, res) => {
        if (err) return console.log('The API returned an error: ' + err);
        console.log(JSON.stringify(res.data))
        console.log(JSON.stringify(res.data.files))
        const files = res.data.files;
        if (files.length) {
          console.log('Files:');
          files.map((file) => {
            console.log(`${file.name} (${file.id})`);
          });
        } else {
          console.log('No files found.');
        }
      });
    }

    function  CreateFolderInGoogleDrive() {
        console.log('CreateFolderInGoogleDrive() was called')
        var fileMetadata = {
            auth: jwtClient,
            'name': 'OfficService',
            'mimeType': 'application/vnd.google-apps.folder',
            'parents':['12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR']
          };
          drive.files.create({
            resource: fileMetadata,
            fields: 'id'
          },(err, file)=> {
            if (err) {
              // Handle error
              console.error(err);
            } else {
             console.log('***parent****'+ file.data.id) 
           
            }
          });
        }

Note: Drive folder "12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR" is already shared with Service account email ID.

Here are some of the results of console log that reflect where it failed.

token******{"access_token":"**********","token_type":"Bearer","expiry_date":1593865140000,"refresh_token":"jwt-placeholder"}

listFolderInGoogleDrive() was called

CreateFolderInGoogleDrive() was called

Error: Login Required

I guess, I am not using token to authenticate. Please help me with Node.js code to use this token to authenticate service account.

1 Answers

I would like to modify the following modification.

Modification points:

  • At exports.handler = async (req, res) => {}, the last } is not used. So your script is not complete. Please be careful this.
    • From your question, I thought that this might be the miss-copy of the script.
  • In your script, jwtClient is not used at listFolderInGoogleDrive() and CreateFolderInGoogleDrive(). I thought that this might be the reason of your issue.
  • At CreateFolderInGoogleDrive(), auth: jwtClient is required to be used in the object of {resource: fileMetadata, fields: "id"}.
    • But in this case, I would like to propose to include jwtClient in drive like google.drive({ version: "v3", auth: jwtClient }).

When above points are reflected to your script, it becomes as follows. In this case, the functions of authWithServicePrivateKey, listFolderInGoogleDrive and CreateFolderInGoogleDrive are modified.

Modified script:

function authWithServicePrivateKey(jwtClient) {
  // Modified
  jwtClient.authorize(function (err) {
    if (err) {
      console.log("Could not connect***!" + err);
      return;
    }
  });
  drive = google.drive({ version: "v3", auth: jwtClient }); // Added
  listFolderInGoogleDrive();
  CreateFolderInGoogleDrive();
}

//Google Drive API
function listFolderInGoogleDrive() {
  console.log("listFolderInGoogleDrive() was called");
  drive.files.list(
    {
      //   auth: jwtClient,  // Removed
      pageSize: 10,
      fields: "nextPageToken, files(id, name)",
    },
    (err, res) => {
      if (err) return console.log("The API returned an error: " + err);
      console.log(JSON.stringify(res.data));
      console.log(JSON.stringify(res.data.files));
      const files = res.data.files;
      if (files.length) {
        console.log("Files:");
        files.map((file) => {
          console.log(`${file.name} (${file.id})`);
        });
      } else {
        console.log("No files found.");
      }
    }
  );
}

function CreateFolderInGoogleDrive() {
  console.log("CreateFolderInGoogleDrive() was called");
  var fileMetadata = {
    // auth: jwtClient,  // Removed
    name: "OfficService",
    mimeType: "application/vnd.google-apps.folder",
    parents: ['12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR'],
  };
  drive.files.create(
    {
      resource: fileMetadata,
      fields: "id",
    },
    (err, file) => {
      if (err) {
        // Handle error
        console.error(err);
      } else {
        console.log("***parent****" + file.data.id);
      }
    }
  );
}

Note:

  • In this modification, it supposes that you have already been able to get and put values for Google Drive using Drive API with your service account. Please be careful this.

Added:

When you want to retrieve the file list of the files you created manually, please modify the scope as follows.

From:

['https://www.googleapis.com/auth/drive.file'],

To:

['https://www.googleapis.com/auth/drive'],
  • About the scope of https://www.googleapis.com/auth/drive.file, the official document says as follows.

    Per-file access to files created or opened by the app. File authorization is granted on a per-user basis and is revoked when the user deauthorizes the app.

And also, you want to retrieve the file list of only the shared folder of 12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR, please modify as follows.

From:

drive.files.list({
    auth: jwtClient,
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
  }, (err, res) => {

To:

drive.files.list({
    auth: jwtClient,
    pageSize: 10,
    fields: 'nextPageToken, files(id, name)',
    q: "'12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR' in parents",  // Added
  }, (err, res) => {
Related