forked from seetransparent/addax
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
56 lines (47 loc) · 1.48 KB
/
server.js
File metadata and controls
56 lines (47 loc) · 1.48 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
const _ = require('lodash');
const express = require('express');
const { exec } = require('child_process');
const { readAuthFile } = require('./authentication.js');
// -------------------------
// authentication
async function authenticateUser(token, rootDirectory) {
const auth = await readAuthFile();
return _.get(auth, token, null) === rootDirectory;
}
// -------------------------
// s3 presigning
function presignPath(config, userDir, path) {
const s3path = `s3://${config.rootPath}/${userDir}/${path}`;
const s3command = `aws s3 presign --expires-in 604800 ${s3path}`;
return new Promise((resolve, reject) => {
exec(s3command, (err, stdout, stderr) => {
if (err) reject(err);
else if (stderr !== '') reject(new Error(stderr));
else resolve(stdout.slice(0, -1));
});
});
}
// -------------------------
// webapp
module.exports = (config, options = {}) => {
const app = express();
app.get('/:root/*', async (req, res) => {
const { root, 0: path } = req.params;
const { token } = req.query;
if (root && path && token && await authenticateUser(token, root)) {
try {
console.log(`[${new Date()}][access]`, root, path);
res.redirect(await presignPath(config, root, path));
} catch (err) {
console.error(`[${new Date()}][ERROR]`, err);
res.sendStatus(500);
}
} else {
res.sendStatus(404);
}
});
app.get('*', (req, res) => {
res.sendStatus(404);
});
app.listen(options);
};