Skip to content

Commit

Permalink
fix: use fastify validation for the request body
Browse files Browse the repository at this point in the history
bonus: fixed how the deletion of files is handled, as currently it did not work as intended
  • Loading branch information
bjarneo committed Mar 9, 2024
1 parent cd91dbf commit b7c01ac
Showing 1 changed file with 32 additions and 21 deletions.
53 changes: 32 additions & 21 deletions src/server/controllers/download.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,33 +5,44 @@ import prisma from '../services/prisma.js';
import { isValidSecretId } from '../helpers/regexp.js';

async function downloadFiles(fastify) {
fastify.post('/', async (request, reply) => {
const { key, secretId } = request.body;

if (!isValidSecretId.test(secretId)) {
return reply.code(403).send({ error: 'Not a valid secret id' });
}

const fileKey = sanitize(key);

const file = await fileAdapter.download(fileKey);
fastify.post(
'/',
{
schema: {
body: {
type: 'object',
required: ['key', 'secretId'],
properties: {
key: { type: 'string' },
secretId: { type: 'string' },
},
},
},
},
async (request, reply) => {
const { key, secretId } = request.body;

if (!isValidSecretId.test(secretId)) {
return reply.code(400).send({ error: 'Not a valid secret id' });
}

const secret = await prisma.secret.findFirst({ where: { id: secretId } });
const fileKey = sanitize(key);

if (secret?.preventBurn !== 'true' && Number(secret?.maxViews) === 1) {
await prisma.secret.delete({ where: { id: secretId } });
const file = await fileAdapter.download(fileKey);

if (secret?.file) {
const { key } = JSON.parse(secret?.file);
const secret = await prisma.secret.findFirst({ where: { id: secretId } });

await fileAdapter.remove(key);
// When the secret is null, we delete the file.
// The deletion will happen in the secrets controller
if (!secret) {
await fileAdapter.remove(fileKey);
}
}

return reply.code(201).send({
content: file,
});
});
return reply.code(201).send({
content: file,
});
}
);
}

export default downloadFiles;

0 comments on commit b7c01ac

Please sign in to comment.