使用Google Platform Bucket

时间:2018-02-17 04:46:51

标签: node.js google-cloud-platform google-cloud-storage

我正在创建一个存储桶并通过我的node.js API将一个index.html文件添加到存储桶中。但是,当我尝试访问该网站时,它给了我这个错误。

AccessDeniedAccess denied.

我做了一些调查,发现this article有关运行终端代码以更新Google Cloud Bucket的安全首选项。但是,我的应用程序的性质使我无法在每次创建存储桶时通过终端手动执行此操作。

如何为每个创建的存储桶自动完成此操作?

这是我用于创建存储桶的Node.Js代码。

exports.createDefaultBucket = functions.https.onRequest((req, res) => {
cors(req, res, () => {

    res.header("Access-Control-Allow-Origin", "*");

    var bucketName = req.body.siteName;

    var defaultIndex = '';
    var defaultCss   = '';

    if(!bucketName) {
        res.send('Bucket name is required!');
    } else {
        storage.createBucket(bucketName).then(() => {
            storage.bucket(bucketName).makePublic().then((response) => {
                console.log(response);
                storage.bucket(bucketName).upload(defaultIndex).then(() => {
                    //storage.bucket(bucketName).upload(defaultCss).then(() => {
                        res.send(bucketName+' was created, made public, has default index file and index location is set!');
                    //})
                })
            }).catch(err => {
                res.send(err);
            })
        }).catch(err => {
            res.send(err);
        });
    }

});
});

1 个答案:

答案 0 :(得分:1)

我不确定makePublic究竟做了什么,但它可能没有更新defaultObjectAcl。根据makePublic上的文档,您可能需要包含该选项以更新文件..但这可能只会更新现有文件。

https://cloud.google.com/nodejs/docs/reference/storage/1.4.x/Bucket#makePublic

//-
// Make the bucket and its contents publicly readable.
//-
var opts = {
  includeFiles: true
};

bucket.makePublic(opts, function(err, files) {
  // `err`:
  //    The first error to occur, otherwise null.
  //
  // `files`:
  //    Array of files successfully made public in the bucket.
});

我建议改用IAM。

https://cloud.google.com/storage/docs/access-control/iam-roles https://cloud.google.com/nodejs/docs/reference/storage/1.4.x/Bucket#iam

bucket.iam
  .getPolicy()
  .then(results => {
    const policy = results[0];

    // Adds the new roles to the bucket's IAM policy
    policy.bindings.push({
      // storage.objectViewers role grants buckets.list and objects.get
      role: 'roles/storage.objectViewers',
      members: 'allUsers',
    });

    // Updates the bucket's IAM policy
    return bucket.iam.setPolicy(policy);
  })