wikijs-fork/server/controllers/upload.js

105 lines
2.7 KiB
JavaScript
Raw 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', multer({
dest: path.join(WIKI.ROOTPATH, 'data/uploads'),
limits: {
fileSize: WIKI.config.uploads.maxFileSize,
files: WIKI.config.uploads.maxFiles
}
}).array('mediaUpload'), 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-05-21 20:45:27 +00:00
folderId: folderId,
2019-05-22 00:58:04 +00:00
assetPath,
userId: req.user.id
})
res.send('ok')
})
router.get('/u', async (req, res, next) => {
res.json({
ok: true
})
})
module.exports = router