Insufficient Permission when trying to create a folder on Google Drive via API(v3)

前端 未结 1 593
轮回少年
轮回少年 2020-12-06 23:57

I am trying to create a folder on my Google Drive via the API. I am using Node, and have created a script that fetches a daily report and would like to via the API, create

相关标签:
1条回答
  • 2020-12-07 00:24

    I think that your script works. So can you confirm the following points again?

    1. About the scope.
      • At Quickstart, the default scope is var SCOPES = ['https://www.googleapis.com/auth/drive.metadata.readonly'];. But in order to use drive.files.create, https://www.googleapis.com/auth/drive is required to be added to the scopes.
      • If you modified the scope, please remove the file of drive-nodejs-quickstart.json. And run the script. By this, the authorization is run and the added scopes are reflected to the refresh token and access token.
    2. About the version of googleapis
      • Recently, it is reported that there are some bugs for googleapis of v27.0.0, v26.0.1 and v25.0.0. So please confirm your version just in case. I use v24.0.0.
    3. Whether Drive API was enabled at API console.
      • About this, I think that from your question, you may have already enabled it.

    If these were not useful for you, I'm sorry.

    Edit :

    var fs = require('fs');
    var readline = require('readline');
    var google = require('googleapis');
    var googleAuth = require('google-auth-library');
    
    // If modifying these scopes, delete your previously saved credentials
    // at ~/.credentials/drive-nodejs-quickstart.json
    var SCOPES = ['https://www.googleapis.com/auth/drive'];
    var TOKEN_DIR = './';
    var TOKEN_PATH = 'drive-nodejs-quickstart.json';
    
    // 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
      // Drive API.
      authorize(JSON.parse(content), createFolder);
    });
    
    /**
     * 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) {
      fs.writeFile(TOKEN_PATH, JSON.stringify(token));
      console.log('Token stored to ' + TOKEN_PATH);
    }
    
    /**
     * Lists the names and IDs of up to 10 files.
     *
     * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
     */
    function createFolder(auth) {
          const drive = google.drive('v3');
          console.log('auth:', auth);
          const fileMetadata = {
            'name': 'daily-report',
            'mimeType': 'application/vnd.google-apps.folder',
            'parents': ['1P924MEzU_1VoL6OOvWPHSo6vb1u9u0a9'],
          };
    
          drive.files.create({
            auth: auth,
            resource: fileMetadata,
            fields: 'id',
          }, function(err, file) {
            if (err) {
              // Handle error
              console.error(err.message);
            } else {
              console.log('Folder Id: ', file.id);
            }
          });
        }
    
    0 讨论(0)
提交回复
热议问题