mirror of
https://github.com/certd/certd.git
synced 2026-06-28 22:47:35 +08:00
chore: 优化私有图片上传和查看逻辑
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
/// <reference types="mocha" />
|
||||
/// <reference types="node" />
|
||||
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { FileService } from "./file-service.js";
|
||||
|
||||
function createUploadFile(key: string) {
|
||||
const uploadRootDir = "./data/upload";
|
||||
const filePath = path.join(uploadRootDir, key);
|
||||
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
||||
fs.writeFileSync(filePath, "test");
|
||||
return filePath;
|
||||
}
|
||||
|
||||
describe("FileService.getFile", () => {
|
||||
let cwd: string;
|
||||
let oldCwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
oldCwd = process.cwd();
|
||||
cwd = fs.mkdtempSync(path.join(os.tmpdir(), "certd-file-service-"));
|
||||
process.chdir(cwd);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(oldCwd);
|
||||
fs.rmSync(cwd, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it("allows admin to read another user's private file", () => {
|
||||
const service = new FileService();
|
||||
const userIdMd5 = Buffer.from(Buffer.from("2").toString("base64")).toString("hex");
|
||||
const key = `/private/${userIdMd5}/2026_05_25/qr.png`;
|
||||
const expectedPath = createUploadFile(key);
|
||||
|
||||
const filePath = service.getFile(key, 1, true);
|
||||
|
||||
assert.equal(filePath, expectedPath);
|
||||
});
|
||||
});
|
||||
@@ -56,7 +56,7 @@ export class FileService {
|
||||
return key;
|
||||
}
|
||||
|
||||
getFile(key: string, userId?: number) {
|
||||
getFile(key: string, userId?: number, allowAnyPrivateUser = false) {
|
||||
if (!key) {
|
||||
throw new ParamException('参数错误');
|
||||
}
|
||||
@@ -70,7 +70,7 @@ export class FileService {
|
||||
const keyArr = key.split('/');
|
||||
const permission = keyArr[1];
|
||||
const userIdMd5 = keyArr[2];
|
||||
if (permission !== 'public') {
|
||||
if (permission !== 'public' && !allowAnyPrivateUser) {
|
||||
//非公开文件需要验证用户
|
||||
const userIdStr = Buffer.from(Buffer.from(userIdMd5, 'hex').toString('base64')).toString();
|
||||
const userIdInt: number = parseInt(userIdStr, 10);
|
||||
|
||||
Reference in New Issue
Block a user