-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
upload-validation.js
43 lines (33 loc) · 1.33 KB
/
upload-validation.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
// NOTE: this middleware was extracted from Ghost core validation for theme uploads
// might be useful to unify this logic in the future if it's extracted to separate module
const path = require('path');
const errors = require('ghost-ignition').errors;
const checkFileExists = function checkFileExists(fileData) {
return !!(fileData.mimetype && fileData.path);
};
const checkFileIsValid = function checkFileIsValid(fileData, types, extensions) {
const type = fileData.mimetype;
if (types.includes(type) && extensions.includes(fileData.ext)) {
return true;
}
return false;
};
module.exports = function uploadValidation(req, res, next) {
const extensions = ['.zip'];
const contentTypes = ['application/zip', 'application/x-zip-compressed', 'application/octet-stream'];
req.file = req.file || {};
req.file.name = req.file.originalname;
req.file.type = req.file.mimetype;
if (!checkFileExists(req.file)) {
return next(new errors.ValidationError({
message: `"Please select a zip file.`
}));
}
req.file.ext = path.extname(req.file.name).toLowerCase();
if (!checkFileIsValid(req.file, contentTypes, extensions)) {
return next(new errors.UnsupportedMediaTypeError({
message: 'Please select a valid zip file.'
}));
}
next();
};