-
Notifications
You must be signed in to change notification settings - Fork 44
/
app.js
executable file
·424 lines (336 loc) · 10.6 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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
if (process.env.NEWRELIC)
require('newrelic');
var _ = require('lodash');
var http = require('http');
var express = require('express');
var cookieParser = require('cookie-parser');
var compress = require('compression');
var connectAssets = require('connect-assets');
var sessions = require('client-sessions');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var errorHandler = require('errorhandler');
var csrf = require('lusca').csrf();
var methodOverride = require('method-override');
var crypto = require('crypto')
var streamFile = require('./lib/streamFile');
var flash = require('express-flash');
var fsPath = require('path');
var EventEmitter = require('events').EventEmitter;
var mongoose = require('mongoose');
mongoose.Promise = global.Promise // http://mongoosejs.com/docs/promises.html
var passport = require('passport');
var expressValidator = require('express-validator');
var exphbs = require('express-handlebars');
var diyHbsHelpers = require('diy-handlebars-helpers');
var hbsHelpers = require('./lib/hbs-helpers');
var templateCache = require('./lib/templateCache').templateCache
// Framework controllers (see below for asset controllers)
var homeController = require('./controllers/homeController');
var vizor2TeaserController = require('./controllers/vizor2TeaserController')
var userController = require('./controllers/userController');
// Threesixty site controller
var threesixtyController = require('./controllers/threesixty');
// API keys + Passport configuration
var secrets = require('./config/secrets');
var passportConf = require('./config/passport');
var OscServer = require('./lib/osc-server').OscServer;
var WsChannelServer = require('./lib/wschannel-server').WsChannelServer;
var EditorChannelServer = require('./lib/editorChannelServer').EditorChannelServer;
var config = require('./config/config.js');
let CloudFileSystemImpl
if (config.server.useCDN)
CloudFileSystemImpl = require('./lib/cloudStorage')
else
CloudFileSystemImpl = require('./lib/gridfs-storage')
var argv = require('minimist')(process.argv.slice(2));
var listenHost = process.env.ENGI_BIND_IP || argv.i || config.server.host;
var listenPort = process.env.ENGI_BIND_PORT || argv.p || config.server.port;
var minute = 60 * 1000;
var hour = 60 * minute;
var day = hour * 24;
var week = day * 7;
var csrfExclude = [
'/this-url-will-bypass-csrf'
];
var app = express();
// keep track of process startup time
process.startTime = Date.now()
app.events = new EventEmitter()
// view engine setup
app.set('views', fsPath.join(__dirname, 'views'));
var releaseMode = process.env.NODE_ENV === 'production'
var hbs = exphbs.create({
defaultLayout: releaseMode ? 'main-bundled' : 'main',
partialsDir: [
{dir:'views/partials'},
{dir:'views/server/partials', namespace: 'srv'}
],
helpers: _.extend(
diyHbsHelpers,
hbsHelpers,
templateCache.helper()
)
})
templateCache.setHbs(hbs.handlebars)
templateCache.compile()
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.use((req, res, next) => {
// Google Cloud Load Balancer: redirect to https if not secure
var fwdProto = req.get('x-forwarded-proto')
if (!fwdProto)
return next()
if (fwdProto !== 'https')
return res.redirect('https://' + req.get('host') + req.url)
next()
})
app.use((req,res,next) => { // allow some context through to handlebars engine/helpers automatically
hbs.handlebars._request = {}
for (var key of ['hostname', 'ip', 'query', 'headers', 'method', 'params', 'secure', 'xhr', 'url', 'originalUrl']) {
hbs.handlebars._request[key] = Object.freeze(_.extend(req[key]))
}
Object.freeze(hbs.handlebars._request)
next()
})
app.use(compress())
app.use(connectAssets({
paths: [
fsPath.join(__dirname, 'browser/style')
],
helperContext: app.locals
}));
if (!releaseMode)
app.use(morgan('dev'))
app.use(bodyParser.json({
limit: 1024 * 1024 * 128
}));
app.use(bodyParser.urlencoded( {
extended: true,
limit: 1024 * 1024 * 128
}));
app.use(expressValidator());
app.use(methodOverride());
// parse the domain out from the FQDN and use it as the cookie domain
// this way 360.vizor.io and vizor.io will use the same cookie
var fqdn = process.env.FQDN || ''
var domainFromFqdn = fqdn.split('.').splice(-2).join('.')
app.use(cookieParser());
app.use(sessions({
cookieName: 'vs070',
requestKey: 'session',
cookie: {
domain: domainFromFqdn,
},
secret: secrets.sessionSecret,
duration: week,
activeDuration: day
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// app.use(function(req, res, next)
// {
// // CSRF protection.
// if (_.contains(csrfExclude, req.path))
// return next();
// csrf(req, res, next);
// });
app.use(function(req, res, next) {
if (!req.user) {
req.session.userId = crypto.randomBytes(12).toString('hex')
} else {
req.session.userId = req.user._id
}
res.locals.user = req.user
res.locals.KEY_MIXPANEL = process.env.KEY_MIXPANEL
res.locals.KEY_GTM = process.env.KEY_GTM
next();
});
app.use(function(req, res, next) {
// Remember original destination before login.
var path = req.path.split('/')[1];
if (/auth||assets|login|logout|signup|img|fonts|favicon/i.test(path)) {
return next();
}
req.session.returnTo = req.path;
next();
});
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
if (req.headers['access-control-request-headers'])
res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers'])
next();
});
app.use(function(req, res, next) {
if (req.url.indexOf('?_') > -1)
req.url = req.url.substring(0, req.url.indexOf('?_'));
next();
});
// old static flat files
app.use('/data', express.static(
fsPath.join(__dirname, 'browser', 'data'),
{ maxAge: week * 52 }
)
)
// accounts
app.get('/login', userController.getLogin);
app.post('/login', userController.postLogin);
app.post('/login.json', userController.postLogin);
app.get('/logout', userController.logout);
app.get('/forgot', userController.getForgot);
app.post('/forgot', userController.postForgot);
app.get('/reset/:token', userController.getReset);
app.post('/reset/:token', userController.postReset);
app.get('/signup', userController.getSignup);
app.post('/signup', userController.postSignup);
app.post('/account/exists', userController.checkUserName);
app.post('/account/email/exists', userController.checkEmailExists);
app.get('/account', passportConf.isAuthenticated, userController.getAccount)
app.post('/account/profile', passportConf.isAuthenticated, userController.postUpdateProfile);
app.get('/account/profile', passportConf.isAuthenticated, userController.getAccountProfile);
app.post('/account/password', passportConf.isAuthenticated, userController.postUpdatePassword);
app.post('/account/delete', passportConf.isAuthenticated, userController.postDeleteAccount);
app.get('/account/unlink/:provider', passportConf.isAuthenticated, userController.getOauthUnlink);
app.get('/about', homeController.about)
// begin 360 routing
app.get('/v/:graph', function(req, res, next) {
switch (req.hostname) {
case '360.vizor.io':
case '360.vizor.lol':
res.locals.layout = 'threesixty'
}
next()
})
app.get('/featured', function(req, res, next) {
switch (req.hostname) {
case '360.vizor.io':
case '360.vizor.lol':
return threesixtyController.featured(req, res, next)
default:
return next()
}
})
app.get('/', function(req, res, next) {
switch (req.hostname) {
case '360.vizor.io':
case '360.vizor.lol':
return res.redirect(301, 'https://vizor.io/new')
default:
return homeController.index(req, res, next)
}
})
app.get('/threesixty', threesixtyController.index)
app.get('/threesixty/featured', threesixtyController.featured)
// end 360 routing
mongoose.connect(secrets.db);
mongoose.connection.on('error', function(err) {
throw err
})
mongoose.connection.on('connected', (connection) => {
setupModelRoutes(mongoose.connection.db)
})
function setupModelRoutes(mongoConnection) {
var modelRoutes = require('./modelRoutes.js')
const cloudStorage = new CloudFileSystemImpl()
// stat() files in cloud storage
app.get(/^\/stat\/.*/, function(req, res) {
var path = req.path.replace(/^\/stat/, '');
cloudStorage.stat(path)
.then(function(stat) {
if (!stat)
return res.json({ error: 404 })
delete stat._id
res.header('Cache-Control', 'public')
return res.json(stat)
})
})
// get files from cloud storage
app.get(/^\/data\/.*/, function(req, res, next) {
return streamFile(req, res, next, cloudStorage)
.catch(next)
});
// allow strong caching for bundles etc.
app.get([
'/dist/*',
'/vendor/*',
'/images/*',
'/fonts/*',
'/docs/*'
], function(req, res, next) {
res.setHeader('Cache-Control', 'public, max-age=604800');
next();
});
// minimal caching for frequently updating things
app.use([
'/style/*',
'/plugins/plugins.json',
'/vizor/patches', // system patch list
],
function(req, res, next) {
res.setHeader('Cache-Control', 'public, must-revalidate, max-age=300');
next();
}
);
if (!releaseMode) {
app.use(function(req, res, next) {
res.setHeader('Cache-Control', 'no-cache')
next()
})
}
// drop the second parameter (timestamp) in meta-scripts
app.use('/meta-scripts', function(req, res, next) {
req.url = '/' + req.url.split('/').splice(2).join('/')
next()
}, express.static(
fsPath.join(__dirname, 'browser', 'scripts'),
{ maxAge: week * 52 }
))
app.use(['/node_modules'],
express.static(fsPath.join(__dirname, 'node_modules'))
)
app.use(express.static(fsPath.join(__dirname, 'browser'),
{ maxAge: hour }))
// remap /scripts to /dist in production
app.use('/scripts', express.static(
fsPath.join(__dirname, 'browser', 'dist'),
{ maxAge: week * 52 }
)
)
app.use('/common', express.static(fsPath.join(__dirname, 'common'),
{ maxAge: hour }))
// --------------------------------------------------
/**
* wire up model routes
**/
modelRoutes.setupDefaultRoutes(
app,
cloudStorage,
mongoConnection,
passportConf
)
// --------------------------------------------------
var httpServer = http.createServer(app)
httpServer.listen(listenPort, listenHost)
if (config.server.enableOSC)
new OscServer().listen(httpServer)
if (config.server.enableChannels) {
new WsChannelServer().listen(httpServer)
var ecs = new EditorChannelServer()
ecs.listen(httpServer)
}
app.use(function(err, req, res, next) {
console.error(err.message, err.stack);
res.status(err.status || 500);
if (req.xhr)
return res.json({ success: false, message: err.message });
res.render('error', {
layout: 'errorlayout',
message: err.message,
error: {}
});
});
app.use(errorHandler());
app.events.emit('ready')
}
module.exports = app;