简体   繁体   中英

Put permissions on a sheet when create a spreadsheet with Google API

I am using Google's Spreadsheets API in NodeJS and I know how I can create a Spreadsheet with the following code

const auth = new GoogleAuth({
    keyFile: 'src/credentials.json',
    scopes: "https://www.googleapis.com/auth/spreadsheets"
})

const client = await auth.getClient()

const googleSheets = google.sheets({version:"v4", auth: client})

let resource = {
    properties: {
        title: 'Test'
    },
}

googleSheets.spreadsheets.create(
    {
        resource,
        fields: 'spreadsheetId'
    }, 
    (err, spreadsheet) =>{
        if (err) {
          console.log(err);
        } else {
          console.log(`${JSON.stringify(spreadsheet)}`);
        }
    }
)

This returns the ID of the Spreadsheet and more information, but my problem is that as much as I have searched, I have not found how to give permissions to an email to access the Spreadsheet.

You will have to add google drive scope/permission in code while getting access token

const SCOPES = [
'https://www.googleapis.com/auth/spreadsheets.readonly',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/drive.file'
];

and then use following code after the code that you've already written.

// PERMISSIONS
const spreadsheetId = spreadsheet.data.spreadsheetId;

drive = await google.drive({ version: "v3", auth: client });
const res = await drive.permissions.create({
    resource: {
        type: "user",
        role: "commenter",
        emailAddress: "johnDoe@gmail.com",  // Please set the email address you want to give the permission.
    },
    fileId: spreadsheetId,
    fields: "id",
});
// END PERMISSIONS

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM