Recv/lib/api/upload.js
Mark van Renswoude 45ae38bd66 Admin panel
Added adding and editing of codes
Added code description and message
Added file sizes
Added disk usage footer
2018-04-27 17:13:18 +02:00

127 lines
2.7 KiB
JavaScript

const config = require('../../config');
const express = require('express');
const asyncHandler = require('express-async-handler');
const jwt = require('jsonwebtoken');
const resolvePath = require('resolve-path');
const fs = require('fs');
const async = require('async');
async function checkAuthorization(req, res, onVerified)
{
if (!req.headers.authorization || req.headers.authorization.split(' ')[0] !== 'Bearer')
{
res.sendStatus(400);
return;
}
var token = req.headers.authorization.split(' ')[1];
jwt.verify(token, config.jwtSecret, async (err, decoded) =>
{
try
{
if (err)
{
res.sendStatus(403);
return;
}
if (decoded.code)
await onVerified(decoded);
else
res.sendStatus(400);
}
catch (e)
{
console.log(e);
res.sendStatus(500);
}
});
}
module.exports = (repository, tusServer) =>
{
var router = express.Router();
// Upload API
router.get('/message/:code', asyncHandler(async (req, res) =>
{
var code = await repository.codes.getCode(req.params.code);
if (code === null)
{
res.sendStatus(404);
return;
}
if (!code.messageHTML)
{
res.sendStatus(204);
return;
}
var user = await repository.users.getUser(code.userId);
var name = user !== null ? user.name : null;
res.send({
name: name,
message: code.messageHTML
});
}));
router.post('/complete', asyncHandler(async (req, res) =>
{
if (!req.body.files)
{
res.sendStatus(400);
return;
}
await checkAuthorization(req, res, async (decoded) =>
{
var expiration = null; // TODO set expiration properties
async.each(req.body.files, (item, callback) =>
{
if (!item.id)
{
callback();
return;
}
var fullpath = resolvePath(config.fileUpload.path, item.id);
fs.stat(fullpath, (err, stats) =>
{
item.size = stats.size;
callback();
});
},
async (err) =>
{
if (err)
{
res.sendStatus(500);
return;
}
var uploadId = await repository.uploads.addUpload(decoded.codeUserId, decoded.code, req.body.files, expiration);
res.send({ id: uploadId });
});
});
}));
// Tus upload
const uploadApp = express();
uploadApp.all('*', asyncHandler(async (req, res) =>
{
await checkAuthorization(req, res, async (decoded) =>
{
tusServer.handle(req, res);
});
}));
router.use('/upload', uploadApp);
return router;
}