do not upload wrong photos

This commit is contained in:
2020-10-14 19:06:38 +03:00
committed by Stepan Usatiuk
parent 0dbf4b020e
commit ece1ffd105
2 changed files with 57 additions and 1 deletions

View File

@@ -4,6 +4,7 @@ import { User } from "~entity/User";
import { IAPIResponse } from "~types";
import * as fs from "fs/promises";
import send = require("koa-send");
import { getHash, getSize } from "~util";
export const photosRouter = new Router();
@@ -76,6 +77,14 @@ photosRouter.post("/photos/upload/:id", async (ctx) => {
}
const file = Object.values(files)[0];
const photoHash = await getHash(file.path);
const photoSize = await getSize(file.path);
if (photoHash !== photo.hash || photoSize !== photo.size) {
ctx.throw(400, "Wrong photo");
return;
}
try {
// TODO: actually move file if it's on different filesystems
await fs.rename(file.path, photo.getPath());
@@ -194,7 +203,7 @@ photosRouter.get("/photos/showByID/:id", async (ctx) => {
const photo = await Photo.findOne({ id, user });
if (!photo) {
if (!photo || !(await photo.isUploaded())) {
ctx.throw(404);
return;
}

View File

@@ -9,6 +9,7 @@ import * as fs from "fs/promises";
import { constants as fsConstants } from "fs";
import {
catPath,
dogFileSize,
dogFormat,
dogHash,
@@ -139,6 +140,52 @@ describe("photos", function () {
);
});
it("should not upload a wrong photo", async function () {
const response = await request(callback)
.post("/photos/new")
.set({
Authorization: `Bearer ${seed.user1.toJWT()}`,
"Content-Type": "application/json",
})
.send({
hash: dogHash,
size: dogSize,
format: dogFormat,
} as IPhotosNewPostBody)
.expect(200);
expect(response.body.error).to.be.false;
const photo = response.body.data as IPhotoJSON;
expect(photo.hash).to.be.equal(dogHash);
const dbPhoto = await Photo.findOneOrFail({
id: photo.id,
user: seed.user1.id as any,
});
expect(dbPhoto.hash).to.be.equal(dogHash);
expect(await dbPhoto.isUploaded()).to.be.equal(false);
await request(callback)
.post(`/photos/upload/${photo.id}`)
.set({
Authorization: `Bearer ${seed.user1.toJWT()}`,
"Content-Type": "application/json",
})
.attach("photo", catPath)
.expect(400);
expect(await dbPhoto.isUploaded()).to.be.equal(false);
const showResp = await request(callback)
.get(`/photos/showByID/${photo.id}`)
.set({
Authorization: `Bearer ${seed.user1.toJWT()}`,
})
.expect(404);
});
it("should create a photo but not upload for other user", async function () {
const response = await request(callback)
.post("/photos/new")