首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >错误:匿名调用方没有storage.objects.get访问Google对象的权限

错误:匿名调用方没有storage.objects.get访问Google对象的权限
EN

Stack Overflow用户
提问于 2020-06-04 13:01:28
回答 2查看 3.7K关注 0票数 2

我试图跟踪一个图像大小的教程在火场。我尝试用普通的NodeJS语法重写代码,并借鉴了其他来源的一些想法。下面是我在index.js中的最后代码

代码语言:javascript
运行
复制
const functions = require('firebase-functions')
const { Storage } = require('@google-cloud/storage');
const projectId = "REDACTED INFO"
let gcs = new Storage ({
    projectId
});
const os = require('os');
const path = require('path');



const sharp = require('sharp');
const fs = require('fs-extra');

// // Create and Deploy Your First Cloud Functions
// // https://firebase.google.com/docs/functions/write-firebase-functions


exports.onFileChange = functions.storage.object().onFinalize(async object => {
    const bucket = gcs.bucket(object.bucket);
    const filePath = object.name;


    const fileName = filePath.split('/').pop();
    const bucketDir = path.dirname(filePath);


    const workingDir = path.join(os.tmpdir(), 'thumbs');
    // const tmpFilePath = path.join(workingDir, 'source.png');
    const tmpFilePath = path.join(workingDir, fileName);
    //const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));


    if (fileName.includes('thumb@') || !object.contentType.includes('image')) {
        console.log('exiting function');
        return false;
    }


    // 1. Ensure thumbnail dir exists
    await fs.ensureDir(workingDir);


    // 2. Download Source File
    await bucket.file(filePath).download({
        destination: tmpFilePath
    });

    // 3. Resize the images and define an array of upload promises
    const sizes = [64, 128, 256];

    const uploadPromises = sizes.map(async size => {
        const thumbName = `thumb@${size}_${fileName}`;
        const thumbPath = path.join(workingDir, thumbName);

        // Resize source image
        await sharp(tmpFilePath)
          .resize(size, size)
          .toFile(thumbPath);

        // Upload to GCS
        return bucket.upload(thumbPath, {
            destination: path.join(bucketDir, thumbName)
        });
    });

    // 4. Run the upload operations
    await Promise.all(uploadPromises);

    // 5. Cleanup remove the tmp/thumbs from the filesystem
    return fs.remove(workingDir);
});

exports.onFileDelete = functions.storage.object().onDelete(event => {
    console.log(event);
    console.log('We deleted a file, exit...')
    return;
});

然而,当我试图上传一个图像时,我总是在firebase控制台日志中得到这些错误和警告。

代码语言:javascript
运行
复制
Error: Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.
    at new ApiError (/srv/node_modules/@google-cloud/common/build/src/util.js:59:15)
    at Util.parseHttpRespMessage (/srv/node_modules/@google-cloud/common/build/src/util.js:161:41)
    at Util.handleResp (/srv/node_modules/@google-cloud/common/build/src/util.js:135:76)
    at Duplexify.requestStream.on.on.res (/srv/node_modules/@google-cloud/storage/build/src/file.js:823:31)
    at emitOne (events.js:116:13)
    at Duplexify.emit (events.js:211:7)
    at emitOne (events.js:116:13)
    at DestroyableTransform.emit (events.js:211:7)
    at onResponse (/srv/node_modules/retry-request/index.js:200:19)
    at PassThrough.<anonymous> (/srv/node_modules/retry-request/index.js:152:11) 

代码语言:javascript
运行
复制
MetadataLookupWarning: received unexpected error = URL is not defined code = UNKNOWN 

有人知道我错过了什么步骤吗?如果需要更多的信息,一定要通知我。谢谢。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-08 04:35:26

代码语言:javascript
运行
复制
Try this:

import * as admin from "firebase-admin";
admin.initializeApp(functions.config().firebase);
const gcs = admin.storage();
票数 2
EN

Stack Overflow用户

发布于 2021-10-26 23:18:06

下面是我为初始化客户机API / SDK和管理API / SDK而编写的一些函数

我将在这里包括全部内容,但就这个问题而言,最重要的部分是:

代码语言:javascript
运行
复制
const serviceAccount = getJsonFromFile(`${rootDirname}/service-account-file.json`)
const adminConfig = appConfig.firebase.options
adminConfig.credential = admin.credential.cert(serviceAccount)
adminApp = admin.initializeApp(adminConfig)

生成服务帐户JSON文件的说明是这里

下面是将其放在上下文中的其余代码:

代码语言:javascript
运行
复制
// noinspection ES6CheckImport
import { connectStorageEmulator, getStorage } from 'firebase/storage'
import { initializeApp } from 'firebase/app'
import admin from 'firebase-admin'
import { appConfig } from '../app-config.js'
import { axiosAsyncAwait } from './axios-utils.js'
import axios from 'axios'
import { rootDirname } from './root-dirname.js'
import { getJsonFromFile } from './get-json-from-file.js'

let app
let adminApp
let storage

const areEmulatorsRunning = async () => {
  const emulatorFunctionsPort = appConfig.firebase.emulatorPorts.functions
  // noinspection HttpUrlsUsage
  const pingUrl = `http://${appConfig.domain}:${emulatorFunctionsPort}/${appConfig.firebase.options.projectId}/us-central1/ping`
  const ping = await axiosAsyncAwait(axios.get(pingUrl))
  const emulatorsRunning = ping.success
  return emulatorsRunning
}

export const getFirebaseApp = async (emulate = true) => {
  if (app == null) {
    app = initializeApp(appConfig.firebase.options)
    storage = getStorage(app)
    const useEmulators = emulate && await areEmulatorsRunning()
    if (useEmulators) {
      console.log('using emulators (client API)')
      process.env.PUBSUB_PROJECT_ID = appConfig.firebase.options.projectId
      process.env.PUBSUB_EMULATOR_HOST = `${appConfig.domain}:${appConfig.firebase.emulatorPorts.pubsub}`
      connectStorageEmulator(storage, appConfig.domain, appConfig.firebase.emulatorPorts.storage)
    } else {
      console.log('using real (client API)')
      process.env.GOOGLE_APPLICATION_CREDENTIALS = `${rootDirname}/service-account-file.json` // pubsub authentication
    }
  }
  return { app, storage }
}

export const getFirebaseAdminApp = async (emulate = true) => {
  if (adminApp == null) {
    const serviceAccount = getJsonFromFile(`${rootDirname}/service-account-file.json`)
    const adminConfig = appConfig.firebase.options
    adminConfig.credential = admin.credential.cert(serviceAccount)
    adminApp = admin.initializeApp(adminConfig)
    const useEmulators = emulate && await areEmulatorsRunning()
    if (useEmulators) {
      console.log('using emulators (admin API)')
      process.env.PUBSUB_PROJECT_ID = appConfig.firebase.options.projectId
      process.env.PUBSUB_EMULATOR_HOST = `${appConfig.domain}:${appConfig.firebase.emulatorPorts.pubsub}`
      process.env.FIREBASE_STORAGE_EMULATOR_HOST = `${appConfig.domain}:${appConfig.firebase.emulatorPorts.storage}`
    } else {
      console.log('using real (admin API)')
    }
  }
  return { adminApp, storage: null }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62195261

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档