aboutsummaryrefslogtreecommitdiffhomepage
path: root/server.js
blob: e79dad29e444f652477bba8fe20af6e94afac793 (plain) (blame)
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
#!/usr/bin/env node

'use strict';

var express = require('express'),
    morgan = require('morgan'),
    path = require('path'),
    fs = require('fs'),
    archiver = require('archiver'),
    compression = require('compression'),
    session = require('express-session'),
    serveIndex = require('serve-index'),
    escapeHtml = require('escape-html'),
    bodyParser = require('body-parser'),
    cookieParser = require('cookie-parser'),
    lastMile = require('connect-lastmile'),
    HttpError = require('connect-lastmile').HttpError,
    HttpSuccess = require('connect-lastmile').HttpSuccess,
    multipart = require('./src/multipart'),
    mkdirp = require('mkdirp'),
    auth = require('./src/auth.js'),
    webdav = require('webdav-server').v2,
    files = require('./src/files.js')(path.resolve(__dirname, process.argv[2] || 'files'));


const ROOT_FOLDER = path.resolve(__dirname, process.argv[2] || 'files');
const CONFIG_FILE = path.resolve(__dirname, process.argv[3] || '.config.json');

// Ensure the root folder exists
mkdirp.sync(ROOT_FOLDER);

var config = {
    folderListingEnabled: false
};

function getSettings(req, res, next) {
    res.send({ folderListingEnabled: !!config.folderListingEnabled });
}

function setSettings(req, res, next) {
    return next(new HttpError(400, 'not editable'));
    if (typeof req.body.folderListingEnabled === 'undefined') return next(new HttpError(400, 'missing folderListingEnabled boolean'));

    config.folderListingEnabled = !!req.body.folderListingEnabled;

    fs.writeFile(CONFIG_FILE, JSON.stringify(config), function (error) {
        if (error) return next(new HttpError(500, 'unable to save settings'));

        next(new HttpSuccess(201, {}));
    });
}

// Load the config file
try {
    console.log(`Using config file at: ${CONFIG_FILE}`);
    config = require(CONFIG_FILE);
} catch (e) {
    if (e.code === 'MODULE_NOT_FOUND') console.log(`Config file ${CONFIG_FILE} not found`);
    else console.log(`Cannot load config file ${CONFIG_FILE}`, e);
}

if (typeof config.folderListingEnabled === 'undefined') config.folderListingEnabled = false;

function isRoot(p) {
  return path.join(ROOT_FOLDER, p) === path.join(ROOT_FOLDER, '/');
}

function sendArchive(format) {
  var mime, extension;
  if (format === "zip") {
    mime = "application/zip";
    extension = "zip";
  } else {
    mime = "application/tar+gzip";
    extension = "tar.gz";
  }
  return function(req, res, next) {
    if (isRoot(req.path) || !fs.existsSync(path.join(ROOT_FOLDER, req.path)))
      return res.status(404).sendFile(__dirname + '/frontend/404.html');
    res.writeHead(200, {
      'Content-Type': mime,
      'Content-disposition': 'attachment; filename=' + path.basename(req.path) + '.' + extension
    });
    var archive = archiver(format);
    archive.pipe(res);
    archive.directory(path.join(ROOT_FOLDER, req.path), path.basename(req.path))
    archive.finalize();
  }
}

function rawTemplate(locals, callback) {
  var html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>wget/curl friendly directory listing of ';
  html += locals.directory;
  html += '</title></head><body><ul>\n';
  html += locals.fileList.map(function (file) {
    if (file.name === "..") { return ""; }
    var isDir = file.stat && file.stat.isDirectory();
    var fpath = locals.directory.split('/').map(function (c) { return encodeURIComponent(c); });
    if (!isDir) { fpath.shift(); fpath[0] = ""; }
    fpath.push(encodeURIComponent(file.name));
    return '<li><a href="' + escapeHtml(path.normalize(fpath.join('/'))) + '">' + escapeHtml(file.name) + '</a></li>';
  }).join("\n");
  html += '\n</ul></body></html>';
  callback(null, html);
};

// Setup the express server and routes
var app = express();
var router = new express.Router();

var webdavServer = new webdav.WebDAVServer({
    requireAuthentification: true,
    httpAuthentication: new webdav.HTTPBasicAuthentication(new auth.WebdavUserManager(), 'Cloudron Surfer')
});

webdavServer.setFileSystem('/', new webdav.PhysicalFileSystem(ROOT_FOLDER), function (success) {
    if (success) console.log(`Mounting webdav resource from: ${ROOT_FOLDER}`);
});

var multipart = multipart({ maxFieldsSize: 2 * 1024, limit: '512mb', timeout: 3 * 60 * 1000 });

router.post  ('/api/login', auth.login);
router.post  ('/api/logout', auth.verify, auth.logout);
router.get   ('/api/settings', auth.verify, getSettings);
router.put   ('/api/settings', auth.verify, setSettings);
router.get   ('/api/tokens', auth.verify, auth.getTokens);
router.post  ('/api/tokens', auth.verify, auth.createToken);
router.delete('/api/tokens/:token', auth.verify, auth.delToken);
router.get   ('/api/profile', auth.verify, auth.getProfile);
router.get   ('/api/files/*', auth.verifyIfNeeded, files.get);
router.post  ('/api/files/*', auth.verify, multipart, files.post);
router.put   ('/api/files/*', auth.verify, files.put);
router.delete('/api/files/*', auth.verify, files.del);

app.use('/api/healthcheck', function (req, res) { res.status(200).send(); });
app.use(morgan('dev'));
app.use(compression());
app.use('/api', bodyParser.json());
app.use('/api', bodyParser.urlencoded({ extended: false, limit: '100mb' }));
app.use('/api', cookieParser());
app.use('/api', session({ secret: 'surfin surfin', resave: false, saveUninitialized: false }));
app.use(router);
app.use(webdav.extensions.express('/_webdav', webdavServer));
app.use('/_admin', express.static(__dirname + '/frontend'));
app.use('/raw', function serveRaw(req, res, next) {
  if (isRoot(req.path) || !fs.existsSync(path.join(ROOT_FOLDER, req.path)))
      return res.status(404).sendFile(__dirname + '/frontend/404.html');
  serveIndex(ROOT_FOLDER, { template: rawTemplate })(req, res, next);
});
app.use('/zip', sendArchive("zip"));
app.use('/tar', sendArchive("tar"));
app.use('/', express.static(ROOT_FOLDER));
app.use('/', function welcomePage(req, res, next) {
    if (config.folderListingEnabled || !isRoot(req.path)) return next();
    res.status(200).sendFile(path.join(__dirname, '/frontend/welcome.html'));
});
app.use('/', function (req, res) {
    if (!fs.existsSync(path.join(ROOT_FOLDER, req.path))) return res.status(404).sendFile(__dirname + '/frontend/404.html');

    res.status(200).sendFile(__dirname + '/frontend/public.html');
});
app.use(lastMile());

var server = app.listen(process.env.LISTEN, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log(`Base path: ${ROOT_FOLDER}`);
    console.log();
    console.log(`Listening on http://${host}:${port}`);

    auth.init(config);
});