diff --git a/src/errors/errors.ts b/src/errors/errors.ts index 6e1d00da6..5f7885ce1 100644 --- a/src/errors/errors.ts +++ b/src/errors/errors.ts @@ -5,3 +5,7 @@ export class NotInDBError extends Error { export class ClientError extends Error { name = 'ClientError'; } + +export class PermissionError extends Error { + name = 'PermissionError'; +} diff --git a/src/media/media.service.ts b/src/media/media.service.ts index 197a1e44c..92c96ee49 100644 --- a/src/media/media.service.ts +++ b/src/media/media.service.ts @@ -3,7 +3,7 @@ import { ModuleRef } from '@nestjs/core'; import { InjectRepository } from '@nestjs/typeorm'; import * as FileType from 'file-type'; import { Repository } from 'typeorm'; -import { ClientError } from '../errors/errors'; +import { ClientError, NotInDBError, PermissionError } from '../errors/errors'; import { ConsoleLoggerService } from '../logger/console-logger.service'; import { NotesService } from '../notes/notes.service'; import { UsersService } from '../users/users.service'; @@ -75,4 +75,36 @@ export class MediaService { await this.mediaUploadRepository.save(mediaUpload); return url; } + + public async deleteFile(filename: string, username: string) { + this.logger.debug( + `Deleting '${filename}' for user '${username}'`, + 'deleteFile', + ); + const mediaUpload = await this.findUploadByFilename(filename); + if (mediaUpload.user.userName !== username) { + this.logger.warn( + `${username} tried to delete '${filename}', but is not the owner`, + 'deleteFile', + ); + throw new PermissionError( + `File '${filename}' is not owned by '${username}'`, + ); + } + const backend = this.moduleRef.get(FilesystemBackend); + await backend.deleteFile(filename, mediaUpload.backendData); + await this.mediaUploadRepository.remove(mediaUpload); + } + + public async findUploadByFilename(filename: string): Promise { + const mediaUpload = await this.mediaUploadRepository.findOne(filename, { + relations: ['user'], + }); + if (mediaUpload === undefined) { + throw new NotInDBError( + `MediaUpload with filename '${filename}' not found`, + ); + } + return mediaUpload; + } }