Step toward a one-page application
[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 var UserModel = require(path.join(__dirname, "models", "User"));
9
10 var app = express();
11
12 app.use(favicon(path.join(__dirname, "public", "images", "favicon", "favicon.ico")));
13
14 if (app.get('env') === 'development')
15 {
16 // Full logging in development mode
17 app.use(logger('dev'));
18 }
19 else
20 {
21 // http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/
22 app.set('trust proxy', true);
23 // In prod, only log error responses (https://github.com/expressjs/morgan)
24 app.use(logger('combined', {
25 skip: function (req, res) { return res.statusCode < 400 }
26 }));
27 }
28
29 // Allow layout.pug to select the right vue file:
30 app.locals.development = (app.get('env') === 'development');
31
32 // view engine setup
33 app.set('views', path.join(__dirname, 'views'));
34 app.set('view engine', 'pug');
35
36 app.use(express.json());
37 app.use(express.urlencoded({ extended: false }));
38 app.use(cookieParser());
39 app.use(sassMiddleware({
40 src: path.join(__dirname, 'public'),
41 dest: path.join(__dirname, 'public'),
42 indentedSyntax: true, // true = .sass and false = .scss
43 sourceMap: true
44 }));
45 app.use(express.static(path.join(__dirname, 'public')));
46
47 // Before showing any page, check + save credentials
48 app.use(function(req, res, next) {
49 req.userId = 0; //means "anonymous"
50 res.locals.user = { name: "" }; //"anonymous"
51 if (!req.cookies.token)
52 return next();
53 UserModel.getOne("sessionToken", req.cookies.token, function(err, user) {
54 if (!!user)
55 {
56 req.userId = user.id;
57 res.locals.user = {
58 id: user.id,
59 name: user.name,
60 email: user.email,
61 notify: user.notify,
62 };
63 }
64 else
65 {
66 // Token in cookies presumably wrong: erase it
67 res.clearCookie("token");
68 }
69 next();
70 });
71 });
72
73 // Routing
74 const routes = require(path.join(__dirname, "routes", "all"));
75 app.use('/', routes);
76
77 // catch 404 and forward to error handler
78 app.use(function(req, res, next) {
79 next(createError(404));
80 });
81
82 // error handler
83 app.use(function(err, req, res, next) {
84 // set locals, only providing error in development
85 res.locals.message = err.message;
86 res.locals.error = req.app.get('env') === 'development' ? err : {};
87 // render the error page
88 res.status(err.status || 500);
89 res.render('error');
90 });
91
92 module.exports = app;