Save current state (unmerged, broken, not working...)
[vchess.git] / app.js
1 var createError = require('http-errors');
2 var express = require('express');
3 var path = require('path');
4 var cookieParser = require('cookie-parser');
5 var logger = require('morgan');
6 var sassMiddleware = require('node-sass-middleware');
7 var favicon = require('serve-favicon');
8
9 var app = express();
10
11 app.use(favicon(path.join(__dirname, "public", "images", "favicon", "favicon.ico")));
12
13 if (app.get('env') === 'development')
14 {
15 // Full logging in development mode
16 app.use(logger('dev'));
17 }
18 else
19 {
20 // http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/
21 app.set('trust proxy', true);
22 // In prod, only log error responses (https://github.com/expressjs/morgan)
23 app.use(logger('combined', {
24 skip: function (req, res) { return res.statusCode < 400 }
25 }));
26 }
27
28 // Allow layout.pug to select the right vue file:
29 app.locals.development = (app.get('env') === 'development');
30
31 // view engine setup
32 app.set('views', path.join(__dirname, 'views'));
33 app.set('view engine', 'pug');
34
35 app.use(express.json());
36 app.use(express.urlencoded({ extended: false }));
37 app.use(cookieParser());
38 app.use(sassMiddleware({
39 src: path.join(__dirname, 'public'),
40 dest: path.join(__dirname, 'public'),
41 indentedSyntax: true, // true = .sass and false = .scss
42 sourceMap: true
43 }));
44 app.use(express.static(path.join(__dirname, 'public')));
45
46 // Before showing any page, check + save credentials
47 app.use(function(req, res, next) {
48 req.loggedIn = false;
49 if (!req.cookies.token)
50 return next();
51 UserModel.getOne("sessionToken", req.cookies.token, function(err, user) {
52 if (!!user)
53 {
54 req.loggedIn = true;
55 res.locals.user = {
56 _id: user._id,
57 name: user.name,
58 email: user.email,
59 notify: user.notify,
60 };
61 }
62 next();
63 });
64 });
65
66 // Routing
67 const routes = require(path.join(__dirname, "routes", "all"));
68 app.use('/', routes);
69
70 // catch 404 and forward to error handler
71 app.use(function(req, res, next) {
72 next(createError(404));
73 });
74
75 // error handler
76 app.use(function(err, req, res, next) {
77 // set locals, only providing error in development
78 res.locals.message = err.message;
79 res.locals.error = req.app.get('env') === 'development' ? err : {};
80 // render the error page
81 res.status(err.status || 500);
82 res.render('error');
83 });
84
85 module.exports = app;