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)
}
});
}
注意:驱动器文件夹“ 12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR”已与服务帐户电子邮件ID共享。
以下是控制台日志的一些结果,它们反映了失败的地方。
令牌****** {“ access_token”:“ **********”,“ token_type”:“承载者”,“到期日期”:1593865140000,“ refresh_token”:“ jwt占位符“}
listFolderInGoogleDrive()被称为
CreateFolderInGoogleDrive()被称为
错误:需要登录
我想,我没有使用令牌进行身份验证。请使用Node.js代码帮助我,以使用此令牌来验证服务帐户。
答案 0 :(得分:3)
我想修改以下修改。
exports.handler = async (req, res) => {}
,不使用最后一个}
。因此您的脚本不完整。请注意这一点。
jwtClient
和listFolderInGoogleDrive()
上未使用CreateFolderInGoogleDrive()
。我认为这可能是您遇到问题的原因。CreateFolderInGoogleDrive()
的{{1}}对象中必须使用auth: jwtClient
。
{resource: fileMetadata, fields: "id"}
一样在jwtClient
中包括drive
。当以上几点反映到您的脚本中时,它如下所示。在这种情况下,google.drive({ version: "v3", auth: jwtClient })
,authWithServicePrivateKey
和listFolderInGoogleDrive
的功能将被修改。
CreateFolderInGoogleDrive
当您要检索手动创建的文件的文件列表时,请按如下所示修改范围。
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);
}
}
);
}
['https://www.googleapis.com/auth/drive.file'],
关于['https://www.googleapis.com/auth/drive'],
的范围,the official document如下所述。
按文件访问由应用程序创建或打开的文件。文件授权是按用户授予的,并且在用户取消对应用程序的授权时将其撤销。
此外,您只想检索https://www.googleapis.com/auth/drive.file
共享文件夹的文件列表,请进行以下修改。
12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR
drive.files.list({
auth: jwtClient,
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (err, res) => {