我正在尝试从Firebase Cloud函数中的Firebase Storage下载文件,其中包含以下类型脚本代码:
exports.getProfileImage = functions.https.onRequest(async (req, resp) => {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
resp.status(401).send("Unauthorized");
return;
}
let detail = "start";
let decodedToken: DecodedIdToken;
try {
const idToken = authHeader.split("Bearer ")[1];
try {
decodedToken = await admin.auth().verifyIdToken(idToken);
} catch (e) {
resp.status(401).send("Unauthorized");
return;
}
const match = RegExp("^\\/(\\w+)$").exec(req.path);
const uid = match && match[1];
if (!uid) {
resp.status(400).send(`Invalid profile image request: ${req.path}`);
return;
}
const filePath = `user/${uid}/profileImage`;
detail = `locating file ${filePath}`;
const ref = admin.storage().bucket().file(filePath);
detail = "Checking file exists";
if (!await ref.exists()) {
resp.status(404).send(`Requested profile image not found: ${req.path}`);
return;
}
detail = `Downloading profile image for ${decodedToken.email} ` +
`from ${ref.cloudStorageURI.href}`;
const [fileContent] = await ref.download();
resp.type("jpeg");
detail = "Sending result";
resp.send(fileContent);
return;
} catch (e) {
if (e instanceof Error) {
resp.status(500).send(`Error while retrieving image: ${e.message}.` +
`Occurred during ${detail}`);
} else {
resp.status(500).send("Unknown error retrieving image");
}
}
});
我不明白为什么exists显然会返回true,但下载会失败,并显示消息“没有这样的对象”。在“download”行上抛出异常,导致类似“Error while retrieving image:没有这样的物体[.]”
我用createReadStream替换下载代码时也会出现类似的错误:
detail = `Downloading profile image for ${decodedToken.email} ` +
`from ${ref.cloudStorageURI.href}`;
const fileReader = ref.createReadStream();
detail = "Setting type to jpeg";
resp.type("jpeg");
detail = "Piping file content to response";
fileReader.on("error", (err) => resp.status(500).send(err.message))
.pipe(resp);
detail = "Sending result";
return;
1条答案
按热度按时间brvekthn1#
该对象显示为存在,但在尝试下载时不可用,这一事实可能表明该问题与安全相关。我做了一些改变,但我认为关键是当我改变了我的Firebase存储规则,允许无条件读取。在此之后,我能够下载,我删除了试图将授权令牌传播到Firebase存储的代码(仅保留在Firebase函数中验证其使用的部分)。也许令牌并不像我怀疑的那样可移植,但显然授权令牌没有让我获得所需的访问权限。
即使这不是最终的解决方案,它也是沿着识别问题的道路迈出的一步。