Logging
Some checks failed
/ Misc Linters (push) Successful in 21s
/ Build App (push) Failing after 21s

This commit is contained in:
Valentin Brandl 2024-08-17 15:39:43 +02:00
parent 1557d2cca9
commit 48948a180a
Signed by: vbrandl
GPG Key ID: CAD4DA1A789125F9

View File

@ -1,7 +1,7 @@
import { writeFileSync, mkdirSync, existsSync } from 'fs';
import { fail } from '@sveltejs/kit';
import type { RequestEvent } from './$types';
import safePath, { storagePath } from '$lib';
import safePath, { storagePath, log } from '$lib';
import { hash } from 'crypto';
import path from 'path';
@ -12,34 +12,44 @@ const mkdirIfNotExists = (path: string) => {
};
export const actions = {
default: async ({ request }: RequestEvent) => {
default: async ({ request, locals }: RequestEvent) => {
var context: any = { requestId: locals.requestId };
const data = await request.formData();
const formFiles = data.getAll('files');
if (!formFiles) {
log.debug(context, 'missing files');
return fail(400, { field: 'files', files: formFiles, missing: true });
} else if (!(formFiles as File[])) {
log.debug(context, 'invalid files');
return fail(400, { field: 'files', files: formFiles, incorrect: true });
}
const files = formFiles as File[];
console.log(files);
const fileNames = files.map((file) => file.name);
context = { fileNames, ...context };
if (files.length === 0) {
log.debug(context, 'empty files');
return fail(400, { field: 'files', files: formFiles, empty: true });
}
const formName = data.get('name');
if (!formName) {
log.debug(context, 'missing name');
return fail(400, { field: 'name', name: formName, missing: true });
} else if (!(formName as string)) {
log.debug(context, 'invalid name');
return fail(400, { field: 'name', name: formName, incorrect: true });
}
const name = formName as string;
context = { name, ...context };
if (!safePath(storagePath, name)) {
log.warn(context, 'Supplied name would cause dir traversal. Rejecting...');
return fail(400, { field: 'name', name: name, incorrect: true });
}
// const name = safePath(formName as string);
log.info(context, 'Uploading files');
files.forEach(async (file) => {
const outPath = `${storagePath}/${name}`;
@ -47,11 +57,13 @@ export const actions = {
const ext = path.extname(file.name);
mkdirIfNotExists(outPath);
const filename = hash('sha1', content);
const fullPath = `${outPath}/${filename}${ext}`;
const filename = `${hash('sha1', content)}${ext}`;
const fullPath = `${outPath}/${filename}`;
context = { file: fullPath, ...context };
if (existsSync(fullPath)) {
console.warn(`${fullPath} has already been uploaded. Skipping...`);
log.debug(context, 'File has already been uploaded. Skipping...');
} else {
log.debug(context, 'saving file');
writeFileSync(fullPath, Buffer.from(await file.arrayBuffer()), { flag: 'a+' });
}
});