|
| 1 | +const path = require('path'); |
| 2 | +const util = require('util'); |
| 3 | +const fs = require('fs'); |
| 4 | +const multer = require('multer'); |
| 5 | +const readChunk = require('read-chunk'); |
| 6 | +const FileType = require('file-type'); |
| 7 | + |
| 8 | +const errors = require('./errors'); |
| 9 | +const log = require('./logger'); |
| 10 | +const config = require('../config'); |
| 11 | + |
| 12 | +const uploadFolderName = `${config.media_dir}/headimages`; |
| 13 | +const allowedExtensions = ['.png', '.jpg', '.jpeg']; |
| 14 | + |
| 15 | +const storage = multer.diskStorage({ // multers disk storage settings |
| 16 | + destination(req, file, cb) { |
| 17 | + cb(null, uploadFolderName); |
| 18 | + }, |
| 19 | + |
| 20 | + // Filename is 4 character random string and the current datetime to avoid collisions |
| 21 | + filename(req, file, cb) { |
| 22 | + const prefix = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 4); |
| 23 | + const date = (new Date()).getTime(); |
| 24 | + const extension = path.extname(file.originalname); |
| 25 | + |
| 26 | + cb(null, `${prefix}-${date}${extension}`); |
| 27 | + }, |
| 28 | +}); |
| 29 | +const upload = multer({ |
| 30 | + storage, |
| 31 | + fileFilter(req, file, cb) { |
| 32 | + const extension = path.extname(file.originalname).toLowerCase(); |
| 33 | + if (!allowedExtensions.includes(extension)) { |
| 34 | + const allowed = allowedExtensions.map((e) => `'${e}'`).join(', '); |
| 35 | + return cb(new Error(`Allowed extensions: ${allowed}, but '${extension}' was passed.`)); |
| 36 | + } |
| 37 | + |
| 38 | + return cb(null, true); |
| 39 | + }, |
| 40 | +}).single('head_image'); |
| 41 | + |
| 42 | +const uploadAsync = util.promisify(upload); |
| 43 | + |
| 44 | +exports.uploadImage = async (req, res) => { |
| 45 | + const oldimg = req.user.image; |
| 46 | + |
| 47 | + // If upload folder doesn't exists, create it. |
| 48 | + if (!fs.existsSync(uploadFolderName)) { |
| 49 | + await fs.promises.mkdir(uploadFolderName, { recursive: true }); |
| 50 | + } |
| 51 | + |
| 52 | + try { |
| 53 | + await uploadAsync(req, res); |
| 54 | + } catch (err) { |
| 55 | + log.error({ err }, 'Could not store image'); |
| 56 | + return errors.makeValidationError(res, err); |
| 57 | + } |
| 58 | + |
| 59 | + // If the head_image field is missing, do nothing. |
| 60 | + if (!req.file) { |
| 61 | + return errors.makeValidationError(res, 'No head_image is specified.'); |
| 62 | + } |
| 63 | + |
| 64 | + // If the file's content is malformed, don't save it. |
| 65 | + const buffer = readChunk.sync(req.file.path, 0, 4100); |
| 66 | + const type = await FileType.fromBuffer(buffer); |
| 67 | + |
| 68 | + const originalExtension = path.extname(req.file.originalname).toLowerCase(); |
| 69 | + const determinedExtension = (type && type.ext ? `.${type.ext}` : 'unknown'); |
| 70 | + |
| 71 | + if (originalExtension !== determinedExtension || !allowedExtensions.includes(determinedExtension)) { |
| 72 | + return errors.makeValidationError(res, 'Malformed file content.'); |
| 73 | + } |
| 74 | + |
| 75 | + await req.user.update({ |
| 76 | + image: req.file.filename |
| 77 | + }); |
| 78 | + |
| 79 | + // Remove old file |
| 80 | + if (oldimg) { |
| 81 | + await fs.promises.unlink(path.join(uploadFolderName, oldimg)); |
| 82 | + } |
| 83 | + |
| 84 | + return res.json({ |
| 85 | + success: true, |
| 86 | + message: 'File uploaded successfully', |
| 87 | + data: req.user.image, |
| 88 | + }); |
| 89 | +}; |
| 90 | + |
| 91 | +exports.removeImage = async (req, res) => { |
| 92 | + if (!req.user.image) { |
| 93 | + return errors.makeValidationError(res, 'No image is specified for the user.'); |
| 94 | + } |
| 95 | + |
| 96 | + await fs.promises.unlink(path.join(uploadFolderName, req.user.image)); |
| 97 | + |
| 98 | + await req.user.update({ |
| 99 | + image: null |
| 100 | + }); |
| 101 | + |
| 102 | + return res.json({ |
| 103 | + success: true, |
| 104 | + message: 'File removed successfully', |
| 105 | + data: req.user.image |
| 106 | + }); |
| 107 | +}; |
0 commit comments