summaryrefslogtreecommitdiff
path: root/app.js
blob: 59f398122fbb2ef2687e051daaf70058551f608f (plain)
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//app
//external modules
var express = require('express');
var toobusy = require('toobusy-js');
var ejs = require('ejs');
var passport = require('passport');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var compression = require('compression')
var session = require('express-session');
var SequelizeStore = require('connect-session-sequelize')(session.Store);
var fs = require('fs');
var imgur = require('imgur');
var formidable = require('formidable');
var morgan = require('morgan');
var passportSocketIo = require("passport.socketio");
var helmet = require('helmet');

//core
var config = require("./lib/config.js");
var logger = require("./lib/logger.js");
var auth = require("./lib/auth.js");
var response = require("./lib/response.js");
var models = require("./lib/models");

//server setup
if (config.usessl) {
    var ca = (function () {
        var i, len, results;
        results = [];
        for (i = 0, len = config.sslcapath.length; i < len; i++) {
            results.push(fs.readFileSync(config.sslcapath[i], 'utf8'));
        }
        return results;
    })();
    var options = {
        key: fs.readFileSync(config.sslkeypath, 'utf8'),
        cert: fs.readFileSync(config.sslcertpath, 'utf8'),
        ca: ca,
        dhparam: fs.readFileSync(config.dhparampath, 'utf8'),
        requestCert: false,
        rejectUnauthorized: false
    };
    var app = express();
    var server = require('https').createServer(options, app);
} else {
    var app = express();
    var server = require('http').createServer(app);
}

//logger
app.use(morgan('combined', {
    "stream": logger.stream
}));

//socket io
var io = require('socket.io')(server);

//others
var realtime = require("./lib/realtime.js");

//assign socket io to realtime
realtime.io = io;

//methodOverride
app.use(methodOverride('_method'));

// create application/json parser
var jsonParser = bodyParser.json();

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({
    extended: false
});

//session store
var sessionStore = new SequelizeStore({
    db: models.sequelize
});

//compression
app.use(compression());

// use hsts to tell https users stick to this
app.use(helmet.hsts({
    maxAge: 31536000 * 1000, // 365 days
    includeSubdomains: true,
    preload: true
}));

// routes without sessions
// static files
app.use('/', express.static(__dirname + '/public', { maxAge: config.staticcachetime }));
app.use('/vendor/', express.static(__dirname + '/bower_components', { maxAge: config.staticcachetime }));

//session
app.use(session({
    name: config.sessionname,
    secret: config.sessionsecret,
    resave: false, //don't save session if unmodified
    saveUninitialized: true, //always create session to ensure the origin
    rolling: true, // reset maxAge on every response
    cookie: {
        maxAge: config.sessionlife,
        expires: new Date(Date.now() + config.sessionlife)
    },
    store: sessionStore
}));

// session resumption
var tlsSessionStore = {};
server.on('newSession', function (id, data, cb) {
    tlsSessionStore[id.toString('hex')] = data;
    cb();
});
server.on('resumeSession', function (id, cb) {
    cb(null, tlsSessionStore[id.toString('hex')] || null);
});

//middleware which blocks requests when we're too busy
app.use(function (req, res, next) {
    if (toobusy()) {
        response.errorServiceUnavailable(res);
    } else {
        next();
    }
});

//passport
app.use(passport.initialize());
app.use(passport.session());

//serialize and deserialize
passport.serializeUser(function (user, done) {
    logger.info('serializeUser: ' + user.id);
    return done(null, user.id);
});
passport.deserializeUser(function (id, done) {
    models.User.findOne({
        where: {
            id: id
        }
    }).then(function (user) {
        logger.info('deserializeUser: ' + user.id);
        return done(null, user);
    }).catch(function (err) {
        logger.error(err);
        return done(err, null);
    });
});

// redirect url with trailing slashes
app.use(function(req, res, next) {
    if ("GET" == req.method && req.path.substr(-1) == '/' && req.path.length > 1) {
        var query = req.url.slice(req.path.length);
        res.redirect(301, config.serverurl + req.path.slice(0, -1) + query);
    } else {
        next();
    }
});

// routes need sessions
//template files
app.set('views', __dirname + '/public');
//set render engine
app.engine('html', ejs.renderFile);
//get index
app.get("/", response.showIndex);
//get 403 forbidden
app.get("/403", function (req, res) {
    response.errorForbidden(res);
});
//get 404 not found
app.get("/404", function (req, res) {
    response.errorNotFound(res);
});
//get 500 internal error
app.get("/500", function (req, res) {
    response.errorInternalError(res);
});
//get status
app.get("/status", function (req, res, next) {
    realtime.getStatus(function (data) {
        res.end(JSON.stringify(data));
    });
});
//get status
app.get("/temp", function (req, res) {
    var host = req.get('host');
    if (config.alloworigin.indexOf(host) == -1)
        response.errorForbidden(res);
    else {
        var tempid = req.query.tempid;
        if (!tempid)
            response.errorForbidden(res);
        else {
            models.Temp.findOne({
                where: {
                    id: tempid
                }
            }).then(function (temp) {
                if (!temp)
                    response.errorNotFound(res);
                else {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.send({
                        temp: temp.data
                    });
                    temp.destroy().catch(function (err) {
                        if (err)
                            logger.error('remove temp failed: ' + err);
                    });
                }
            }).catch(function (err) {
                logger.error(err);
                return response.errorInternalError(res);
            });
        }
    }
});
//post status
app.post("/temp", urlencodedParser, function (req, res) {
    var host = req.get('host');
    if (config.alloworigin.indexOf(host) == -1)
        response.errorForbidden(res);
    else {
        var data = req.body.data;
        if (!data)
            response.errorForbidden(res);
        else {
            if (config.debug)
                logger.info('SERVER received temp from [' + host + ']: ' + req.body.data);
            models.Temp.create({
                data: data
            }).then(function (temp) {
                if (temp) {
                    res.header("Access-Control-Allow-Origin", "*");
                    res.send({
                        status: 'ok',
                        id: temp.id
                    });
                } else
                    response.errorInternalError(res);
            }).catch(function (err) {
                logger.error(err);
                return response.errorInternalError(res);
            });
        }
    }
});
//facebook auth
if (config.facebook) {
    app.get('/auth/facebook',
        passport.authenticate('facebook'));
    //facebook auth callback
    app.get('/auth/facebook/callback',
        passport.authenticate('facebook', {
            failureRedirect: config.serverurl + '/'
        }),
        function (req, res) {
            res.redirect(config.serverurl + '/');
        });
}
//twitter auth
if (config.twitter) {
    app.get('/auth/twitter',
        passport.authenticate('twitter'));
    //twitter auth callback
    app.get('/auth/twitter/callback',
        passport.authenticate('twitter', {
            failureRedirect: config.serverurl + '/'
        }),
        function (req, res) {
            res.redirect(config.serverurl + '/');
        });
}
//github auth
if (config.github) {
    app.get('/auth/github',
        passport.authenticate('github'));
    //github auth callback
    app.get('/auth/github/callback',
        passport.authenticate('github', {
            failureRedirect: config.serverurl + '/'
        }),
        function (req, res) {
            res.redirect(config.serverurl + '/');
        });
    //github callback actions
    app.get('/auth/github/callback/:noteId/:action', response.githubActions);
}
//gitlab auth
if (config.gitlab) {
    app.get('/auth/gitlab',
        passport.authenticate('gitlab'));
    //gitlab auth callback
    app.get('/auth/gitlab/callback',
        passport.authenticate('gitlab', {
            failureRedirect: config.serverurl + '/'
        }),
        function (req, res) {
            res.redirect(config.serverurl + '/');
        });
    //gitlab callback actions
    app.get('/auth/gitlab/callback/:noteId/:action', response.gitlabActions);
}
//dropbox auth
if (config.dropbox) {
    app.get('/auth/dropbox',
        passport.authenticate('dropbox-oauth2'));
    //dropbox auth callback
    app.get('/auth/dropbox/callback',
        passport.authenticate('dropbox-oauth2', {
            failureRedirect: config.serverurl + '/'
        }),
        function (req, res) {
            res.redirect(config.serverurl + '/');
        });
}
//google auth
if (config.google) {
    app.get('/auth/google',
        passport.authenticate('google', { scope: ['profile'] }));
    //google auth callback
    app.get('/auth/google/callback',
        passport.authenticate('google', {
            failureRedirect: config.serverurl + '/'
        }),
        function (req, res) {
            res.redirect(config.serverurl + '/');
        });
}
//logout
app.get('/logout', function (req, res) {
    if (config.debug && req.isAuthenticated())
        logger.info('user logout: ' + req.user.id);
    req.logout();
    res.redirect(config.serverurl + '/');
});
//get history
app.get('/history', function (req, res) {
    if (req.isAuthenticated()) {
        models.User.findOne({
            where: {
                id: req.user.id
            }
        }).then(function (user) {
            if (!user)
                return response.errorNotFound(res);
            var history = [];
            if (user.history)
                history = JSON.parse(user.history);
            res.send({
                history: history
            });
            if (config.debug)
                logger.info('read history success: ' + user.id);
        }).catch(function (err) {
            logger.error('read history failed: ' + err);
            return response.errorInternalError(res);
        });
    } else {
        return response.errorForbidden(res);
    }
});
//post history
app.post('/history', urlencodedParser, function (req, res) {
    if (req.isAuthenticated()) {
        if (config.debug)
            logger.info('SERVER received history from [' + req.user.id + ']: ' + req.body.history);
        models.User.update({
            history: req.body.history
        }, {
            where: {
                id: req.user.id
            }
        }).then(function (count) {
            if (!count)
                return response.errorNotFound(res);
            if (config.debug)
                logger.info("write user history success: " + req.user.id);
        }).catch(function (err) {
            logger.error('write history failed: ' + err);
            return response.errorInternalError(res);
        });
        res.end();
    } else {
        return response.errorForbidden(res);
    }
});
//get me info
app.get('/me', function (req, res) {
    if (req.isAuthenticated()) {
        models.User.findOne({
            where: {
                id: req.user.id
            }
        }).then(function (user) {
            if (!user)
                return response.errorNotFound(res);
            var profile = models.User.parseProfile(user.profile);
            res.send({
                status: 'ok',
                id: req.user.id,
                name: profile.name,
                photo: profile.photo
            });
        }).catch(function (err) {
            logger.error('read me failed: ' + err);
            return response.errorInternalError(res);
        });
    } else {
        res.send({
            status: 'forbidden'
        });
    }
});
//upload to imgur
app.post('/uploadimage', function (req, res) {
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        if (err || !files.image || !files.image.path) {
            response.errorForbidden(res);
        } else {
            if (config.debug)
                logger.info('SERVER received uploadimage: ' + JSON.stringify(files.image));
            imgur.setClientId(config.imgur.clientID);
            try {
                imgur.uploadFile(files.image.path)
                    .then(function (json) {
                        if (config.debug)
                            logger.info('SERVER uploadimage success: ' + JSON.stringify(json));
                        res.send({
                            link: json.data.link.replace(/^http:\/\//i, 'https://')
                        });
                    })
                    .catch(function (err) {
                        logger.error(err);
                        return res.send('upload image error');
                    });
            } catch (err) {
                logger.error(err);
                return res.send('upload image error');
            }
        }
    });
});
//get new note
app.get("/new", response.newNote);
//get publish note
app.get("/s/:shortid", response.showPublishNote);
//publish note actions
app.get("/s/:shortid/:action", response.publishNoteActions);
//get publish slide
app.get("/p/:shortid", response.showPublishSlide);
//get note by id
app.get("/:noteId", response.showNote);
//note actions
app.get("/:noteId/:action", response.noteActions);
//note actions with action id
app.get("/:noteId/:action/:actionId", response.noteActions);
// response not found if no any route matches
app.get('*', function (req, res) {
    response.errorNotFound(res);
});

//socket.io secure
io.use(realtime.secure);
//socket.io auth
io.use(passportSocketIo.authorize({
    cookieParser: cookieParser,
    key: config.sessionname,
    secret: config.sessionsecret,
    store: sessionStore,
    success: realtime.onAuthorizeSuccess,
    fail: realtime.onAuthorizeFail
}));
//socket.io heartbeat
io.set('heartbeat interval', config.heartbeatinterval);
io.set('heartbeat timeout', config.heartbeattimeout);
//socket.io connection
io.sockets.on('connection', realtime.connection);

//listen
function startListen() {
    if (config.usessl) {
        server.listen(config.port, function () {
            logger.info('HTTPS Server listening at port %d', config.port);
            config.maintenance = false;
        });
    } else {
        server.listen(config.port, function () {
            logger.info('HTTP Server listening at port %d', config.port);
            config.maintenance = false;
        });
    }
}

// sync db then start listen
models.sequelize.sync().then(function () {
    // check if realtime is ready
    if (realtime.isReady()) {
        models.Revision.checkAllNotesRevision(function (err, notes) {
            if (err) return new Error(err);
            if (notes.length <= 0) return startListen();
        });
    }
});

// log uncaught exception
process.on('uncaughtException', function (err) {
    logger.error('An uncaught exception has occured.');
    logger.error(err);
    logger.error('Process will exit now.');
    process.exit(1);
});

// gracefully exit
process.on('SIGINT', function () {
    config.maintenance = true;
    // disconnect all socket.io clients
    Object.keys(io.sockets.sockets).forEach(function (key) {
        var socket = io.sockets.sockets[key];
        // notify client server going into maintenance status
        socket.emit('maintenance');
        socket.disconnect(true);
    });
    var checkCleanTimer = setInterval(function () {
        if (realtime.isReady()) {
            models.Revision.checkAllNotesRevision(function (err, notes) {
                if (err) return new Error(err);
                if (notes.length <= 0) {
                    clearInterval(checkCleanTimer);
                    return process.exit(0);
                }
            });
        }
    }, 100);
});