-
Notifications
You must be signed in to change notification settings - Fork 47
/
app.js
198 lines (171 loc) · 6.43 KB
/
app.js
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
'use strict';
/*
Atlas Maker Server
Roberto Toro, 25 July 2014
*/
const nwl = require('neuroweblab');
const fs = require('fs');
const express = require('express');
const compression = require('compression');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const tracer = require('tracer').console({ format: '[{{file}}:{{line}}] {{message}}' });
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const mustacheExpress = require('mustache-express');
const Config = JSON.parse(fs.readFileSync('./cfg.json'));
const https = require('https');
const http = require('http');
global.authTokenMiddleware = nwl.authTokenMiddleware;
const AtlasmakerServer = require('./controller/atlasmakerServer/atlasmakerServer');
const routes = require('./controller/routes/routes');
let MONGO_DB;
const DOCKER_DB = process.env.DB_PORT;
const DOCKER_DEVELOP = process.env.DEVELOP;
if (DOCKER_DB) {
MONGO_DB = DOCKER_DB.replace('tcp://', '') + '/brainbox';
} else {
MONGO_DB = process.env.MONGODB || 'localhost:27017/brainbox';
}
/** @todo Handle the case when MongoDB is not installed */
// var db = monk(MONGO_DB);
/* jslint nomen: true */
const dirname = __dirname; // Local directory
/* jslint nomen: false */
if (DOCKER_DEVELOP === '1') {
// eslint-disable-next-line global-require
const livereload = require('livereload');
// Create a livereload server
const hotServer = livereload.createServer({
// Reload on changes to these file extensions.
exts: ['json', 'mustache'],
// Print debug info
debug: true
});
// Specify the folder to watch for file-changes.
hotServer.watch(__dirname);
tracer.log(`Watching: ${__dirname}`);
}
// eslint-disable-next-line max-statements
const start = async function () {
const app = express();
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
/*
Use the NeuroWebLab (NWL) module for authentication.
NWL will also create the DB. In the future, a series
of functions common to BrainBox and MicroDraw will be
moved to NWL.
*/
await nwl.init({
app,
MONGO_DB,
dirname,
usernameField: 'nickname',
usersCollection: 'user',
projectsCollection: 'project',
annotationsCollection: 'mri'
});
const db = app.db.mongoDB();
//========================================================================================
// Allow CORS
//========================================================================================
app.use(function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
//========================================================================================
// Enable compression
//========================================================================================
app.use(compression());
app.engine('mustache', mustacheExpress());
app.set('views', path.join(dirname, 'templates'));
app.set('view engine', 'mustache');
app.use(favicon(dirname + '/public/favicon.png'));
app.set('trust proxy', 'loopback');
let loggerOptions = {};
if (app.get('env') === 'production') {
loggerOptions = {
skip: function (req, res) { return res.statusCode < 400; }
};
}
app.use(logger(':remote-addr :method :url :status :response-time ms - :res[content-length]', loggerOptions));//app.use(logger('dev'));
app.use(cookieParser());
app.use(express.static(path.join(dirname, 'public')));
if (DOCKER_DEVELOP === '1') {
// eslint-disable-next-line global-require
app.use(require('connect-livereload')());
}
//========================================================================================
// App-wide variables
//========================================================================================
app.use((req, res, next) => {
req.dirname = dirname;
req.db = db;
next();
});
//========================================================================================
// Configure server and web socket
//========================================================================================
const server = http.createServer(app).listen(3001, () => { console.log('Listening http on port 3001'); });
const atlasmakerServer = new AtlasmakerServer(db);
atlasmakerServer.dataDirectory = dirname + '/public';
if (Config.secure) {
const options = {
key: await fs.promises.readFile(Config.ssl_key),
cert: await fs.promises.readFile(Config.ssl_cert)
};
if (Config.ssl_chain) {
options.ca = await fs.promises.readFile(Config.ssl_chain);
}
atlasmakerServer.server = https.createServer(options, app);
} else {
atlasmakerServer.server = http.createServer(app);
}
atlasmakerServer.server.listen(8080, () => {
if (Config.secure) {
console.log('Listening wss on port 8080');
} else {
console.log('Listening ws on port 8080');
}
atlasmakerServer.initSocketConnection();
});
//========================================================================================
// Setup routes
//========================================================================================
routes(app);
//========================================================================================
// Error handlers
//========================================================================================
// // catch 404 and forward to error handler
// app.use(function (req, res, next) {
// console.log('Not found URL requested: ' + req.url);
// next();
// });
// the following middlewares will not be used by express as we need to pass 4 arguments to
// the use method to handle express errors: https://expressjs.com/fr/guide/error-handling.html
// // development error handler
// // will print stacktrace
// if (app.get('env') === 'development') {
// app.use(function (err, req, res) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: err
// });
// });
// }
// // production error handler
// // no stacktraces leaked to user
// app.use(function (err, req, res) {
// res.status(err.status || 500);
// res.render('error', {
// message: err.message,
// error: {}
// });
// });
return { app, server, atlasmakerServer };
};
module.exports = { start };