-
Notifications
You must be signed in to change notification settings - Fork 56
/
attachment-upload.js
67 lines (53 loc) · 1.81 KB
/
attachment-upload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import path from 'path';
import validator from 'validator';
import fp from 'fastify-plugin';
import { fileTypeFromBuffer } from 'file-type';
import fileAdapter from '../services/file-adapter.js';
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types
const notAllowed = [
'application/zip',
'application/x-7z-compressed',
'application/x-tar',
'application/vnd.rar',
'application/ogg',
'application/java-archive',
'application/gzip',
'application/x-bzip2',
'application/x-bzip',
'application/x-cdf',
'application/x-freearc',
];
function acceptedFileType(mimetype) {
if (notAllowed.indexOf(mimetype) > -1) {
return false;
}
if (mimetype.startsWith('image/')) {
return true;
}
if (mimetype.startsWith('application/')) {
return true;
}
if (mimetype.startsWith('text/')) {
return true;
}
return false;
}
export default fp(async (fastify) => {
fastify.decorate('attachment', async (req, reply) => {
const file = await req.body.file;
const { encryptionKey } = req.secret;
if (file.mimetype) {
const fileData = await file.toBuffer();
const metadata = await fileTypeFromBuffer(fileData);
const mime = metadata?.mime ? metadata.mime : file.mimetype.toString();
const ext = metadata?.ext ? metadata.ext : path.extname(file.filename);
if (!acceptedFileType(mime)) {
return reply.code(415).send({
error: `This file type "${mime}" is not supported, yet.`,
});
}
const imageData = await fileAdapter.upload(encryptionKey, fileData);
Object.assign(req.secret, { file: { ext, mime, key: imageData.key } });
}
});
});