Don't throw errors on file not found and delete files that should be deleted on access

This commit is contained in:
Alice Gaudon 2020-07-05 19:44:55 +02:00
parent f7a2603e7f
commit e34c0d46db

View File

@ -1,6 +1,6 @@
import Controller from "wms-core/Controller";
import {REQUIRE_AUTH_MIDDLEWARE, REQUIRE_REQUEST_AUTH_MIDDLEWARE} from "wms-core/auth/AuthComponent";
import {Request, Response} from "express";
import {NextFunction, Request, Response} from "express";
import {BadRequestError, ForbiddenHttpError, NotFoundHttpError, ServerError} from "wms-core/HttpError";
import FileModel from "../models/FileModel";
import {cryptoRandomDictionary} from "wms-core/Utils";
@ -9,6 +9,7 @@ import * as fs from "fs";
import AuthToken from "../models/AuthToken";
import {IncomingForm} from "formidable";
import {FILE_UPLOAD_MIDDLEWARE} from "wms-core/components/ExpressAppComponent";
import Logger from "wms-core/Logger";
const SLUG_DICTIONARY = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
@ -73,9 +74,15 @@ export default class FileController extends Controller {
await this.handleFileUpload(req.body.autogen_url === undefined && req.body.slug ? req.body.slug : await this.generateSlug(10), req, res);
}
protected async downloadFile(req: Request, res: Response): Promise<void> {
protected async downloadFile(req: Request, res: Response, next: NextFunction): Promise<void> {
const file = await FileModel.getBySlug(req.params.slug);
if (!file || file.shouldBeDeleted()) throw new NotFoundHttpError('File', req.url);
if (!file) return next();
if (file.shouldBeDeleted()) {
await fs.unlinkSync(file.storage_path);
await file.delete();
Logger.info('Deleted', file.storage_path, `(${file.real_name})`);
return next();
}
switch (file.storage_type) {
case 'local':
@ -139,12 +146,12 @@ export default class FileController extends Controller {
});
}
protected async deleteFile(req: Request, res: Response): Promise<void> {
protected async deleteFile(req: Request, res: Response, next: NextFunction): Promise<void> {
const slug = req.params.slug;
if (!slug) throw new BadRequestError('Cannot delete nothing.', 'Please provide a slug.', req.url);
const file = await FileModel.getBySlug(req.params.slug);
if (!file) throw new NotFoundHttpError('File', req.url);
if (!file) return next();
if (!file.canDelete(req.models.user!.id!)) throw new ForbiddenHttpError('file', req.url);
switch (file.storage_type) {