在多次调用Google工作表时,API身份验证不适用于第二次调用:请求的身份验证范围不足

时间:2016-11-01 17:07:05

标签: javascript node.js authentication google-sheets-api

所以基本上我在这里所做的就是为了我自己的目的而劫持了google sheet api node.js快速入门指南。这里的一切都很有效,直到它到达我的spreadsheets.batchUpdate,然后一切都变得古怪。

如果我在spreadsheets.batchUpdate中注释掉“auth”初始化,我会收到错误消息:The API returned an error: Error: The request does not have valid authentication credentials.

如果我在spreadsheets.batchUpdate中注释掉“auth”初始化,我会收到错误消息:The API returned an error: Error: Request had insufficient authentication scopes.

我试图对这些调用进行的操作是从表单中获取一些数据,然后删除行,但我无法弄清楚此身份验证问题。

var fs = require('fs');
var updateDB = require('./updateDB.js');
var readline = require('readline');
var google = require('googleapis');
var googleAuth = require('google-auth-library');
var splitData;


// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'sheets.googleapis.com-nodejs-quickstart.json';
var array = [];

var run = {
  runQuickstart : function() {
    // Load client secrets from a local file.
    fs.readFile('client_secret.json', function processClientSecrets(err, content) {
      if (err) {
        console.log('Error loading client secret file: ' + err);
        return;
      }
      // Authorize a client with the loaded credentials, then call the
      // Google Sheets API.
      authorize(JSON.parse(content), listMajors);
    });
  }
}

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var auth = new googleAuth();
  var oauth2Client = new auth.OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token));
  console.log('Token stored to ' + TOKEN_PATH);
}

/**
 * Print the names and majors of students in a sample spreadsheet:
 * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
 */
function listMajors(auth) {
  var sheets = google.sheets('v4');
  sheets.spreadsheets.values.get({
    auth: auth,
    spreadsheetId: '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI',
    range: 'Form Responses 1!A3:X3',
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var rows = response.values;
    //splitData = rows.split(',');
    updateDB.inputFormToDB.apply(this, rows);
    if (rows.length == 0) {
      console.log('No data found.');
    } else {
      console.log('Form Responses');
      for (var i = 0; i < rows.length; i++) {
        var row = rows[i];
        // Print columns A and E, which correspond to indices 0 and 4.
        console.log('%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s', row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9],row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23]);
      }


      var spreadsheetId = '1EV8S8AaAmxF3vP0F6RWxKIUlvF6uFEmsrOFWA1oNBYI';
      var requests = [];
      requests.push({
        "deleteDimension": {
          "range": {
            "sheetId": spreadsheetId,
            "dimension": "ROWS",
            "startIndex": 0,
            "endIndex": 3
          }
        }
      });
      var batchUpdateRequest = {requests: requests}
      var test = auth;
      sheets.spreadsheets.batchUpdate({
        // auth: test,
        spreadsheetId: spreadsheetId,
        resource: batchUpdateRequest
      }, function(err, response) {
        if (err) {
          console.log('The API returned an error: ' + err);
          return;
        }
      });

    }
  });
}

module.exports = run;

1 个答案:

答案 0 :(得分:2)

https://www.googleapis.com/auth/spreadsheets.readonly会给你阅读权。 您需要使用https://www.googleapis.com/auth/spreadsheets范围来更新工作表。

  

https://www.googleapis.com/auth/spreadsheets.readonly

Allows read-only access to the user's sheets and their properties.
  

https://www.googleapis.com/auth/spreadsheets

Allows read/write access to the user's sheets and their properties.