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 共享。
以下是控制台日志的一些结果,反射(reflect)了失败的位置。
token******{"access_token":"************","token_type":"承载","expiry_date":1593865140000,"refresh_token":"jwt-placeholder “}
listFolderInGoogleDrive() 被调用
调用了 CreateFolderInGoogleDrive()
错误:需要登录
我想,我没有使用 token 进行身份验证。请帮助我使用 Node.js 代码来使用此 token 来验证服务帐户。
最佳答案
我想修改以下修改。
修改点:
- 在
exports.handler = async (req, res) => {}
,最后}
未使用。所以你的脚本不完整。请小心这一点。- 从你的问题来看,我认为这可能是脚本的错误复制。
- 在您的脚本中,
jwtClient
未在listFolderInGoogleDrive()
处使用和CreateFolderInGoogleDrive()
。我认为这可能是您出现问题的原因。 - 在
CreateFolderInGoogleDrive()
,auth: jwtClient
需要用在{resource: fileMetadata, fields: "id"}
的对象中。- 但在这种情况下,我建议添加
jwtClient
在drive
喜欢google.drive({ version: "v3", auth: jwtClient })
.
- 但在这种情况下,我建议添加
当以上几点反射(reflect)到您的脚本中时,它会变成如下所示。在这种情况下,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);
}
}
);
}
注意:
- 在此修改中,假设您已经能够通过您的服务帐户使用 Drive API 获取和输入 Google 云端硬盘的值。请小心这一点。
添加:
当您想要检索您手动创建的文件的文件列表时,请修改范围如下。
来自:
['https://www.googleapis.com/auth/drive.file'],
致:
['https://www.googleapis.com/auth/drive'],
关于
https://www.googleapis.com/auth/drive.file
的范围, the official document说如下。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.
而且,您只想检索12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR
的共享文件夹的文件列表。 ,请修改如下。
来自:
drive.files.list({
auth: jwtClient,
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
}, (err, res) => {
致:
drive.files.list({
auth: jwtClient,
pageSize: 10,
fields: 'nextPageToken, files(id, name)',
q: "'12CCq1GGoTyDW_Ox09TZf5BDgaPAjB0AR' in parents", // Added
}, (err, res) => {
关于node.js - 通过服务帐户访问Google Drive : Error: Login Required,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62735018/