wikijs-fork/server/controllers/upload.js

108 lines
2.8 KiB
JavaScript
Raw Permalink Normal View History

const express = require('express')
const router = express.Router()
const _ = require('lodash')
const multer = require('multer')
const path = require('path')
const sanitize = require('sanitize-filename')
/* global WIKI */
/**
* Upload files
*/
router.post('/u', (req, res, next) => {
multer({
dest: path.resolve(WIKI.ROOTPATH, WIKI.config.dataPath, 'uploads'),
limits: {
fileSize: WIKI.config.uploads.maxFileSize,
files: WIKI.config.uploads.maxFiles
}
}).array('mediaUpload')(req, res, next)
}, async (req, res, next) => {
if (!_.some(req.user.permissions, pm => _.includes(['write:assets', 'manage:system'], pm))) {
return res.status(403).json({
succeeded: false,
message: 'You are not authorized to upload files.'
})
} else if (req.files.length < 1) {
return res.status(400).json({
succeeded: false,
message: 'Missing upload payload.'
})
} else if (req.files.length > 1) {
return res.status(400).json({
succeeded: false,
message: 'You cannot upload multiple files within the same request.'
})
}
const fileMeta = _.get(req, 'files[0]', false)
if (!fileMeta) {
return res.status(500).json({
succeeded: false,
message: 'Missing upload file metadata.'
})
}
2019-05-21 20:45:27 +00:00
// Get folder Id
let folderId = null
try {
const folderRaw = _.get(req, 'body.mediaUpload', false)
if (folderRaw) {
2019-05-21 20:45:27 +00:00
folderId = _.get(JSON.parse(folderRaw), 'folderId', null)
if (folderId === 0) {
folderId = null
}
} else {
throw new Error('Missing File Metadata')
}
} catch (err) {
return res.status(400).json({
succeeded: false,
message: 'Missing upload folder metadata.'
})
}
2019-05-21 20:45:27 +00:00
// Build folder hierarchy
let hierarchy = []
if (folderId) {
try {
hierarchy = await WIKI.models.assetFolders.getHierarchy(folderId)
} catch (err) {
return res.status(400).json({
succeeded: false,
message: 'Failed to fetch folder hierarchy.'
})
}
}
// Sanitize filename
fileMeta.originalname = sanitize(fileMeta.originalname.toLowerCase().replace(/[\s,;#]+/g, '_'))
2019-05-21 20:45:27 +00:00
// Check if user can upload at path
2019-05-21 23:01:20 +00:00
const assetPath = (folderId) ? hierarchy.map(h => h.slug).join('/') + `/${fileMeta.originalname}` : fileMeta.originalname
2019-05-21 20:45:27 +00:00
if (!WIKI.auth.checkAccess(req.user, ['write:assets'], { path: assetPath })) {
return res.status(403).json({
succeeded: false,
message: 'You are not authorized to upload files to this folder.'
})
}
2019-05-21 20:45:27 +00:00
// Process upload file
await WIKI.models.assets.upload({
...fileMeta,
2019-10-20 18:42:10 +00:00
mode: 'upload',
2019-05-21 20:45:27 +00:00
folderId: folderId,
2019-05-22 00:58:04 +00:00
assetPath,
user: req.user
})
res.send('ok')
})
router.get('/u', async (req, res, next) => {
res.json({
ok: true
})
})
module.exports = router