Draft Game and Challenge models
[vchess.git] / app.js
CommitLineData
1d184b4c
BA
1var createError = require('http-errors');
2var express = require('express');
3var path = require('path');
4var cookieParser = require('cookie-parser');
5var logger = require('morgan');
6var sassMiddleware = require('node-sass-middleware');
7var favicon = require('serve-favicon');
c018b304 8var UserModel = require(path.join(__dirname, "models", "User"));
1d184b4c 9
1d184b4c
BA
10var app = express();
11
12app.use(favicon(path.join(__dirname, "public", "images", "favicon", "favicon.ico")));
13
14if (app.get('env') === 'development')
15{
16 // Full logging in development mode
17 app.use(logger('dev'));
18}
19else
20{
92342261
BA
21 // http://dev.rdybarra.com/2016/06/23/Production-Logging-With-Morgan-In-Express/
22 app.set('trust proxy', true);
1d184b4c
BA
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
fb1ecbdf 29// Allow layout.pug to select the right vue file:
8d7e2786 30app.locals.development = (app.get('env') === 'development');
fb1ecbdf 31
1d184b4c
BA
32// view engine setup
33app.set('views', path.join(__dirname, 'views'));
34app.set('view engine', 'pug');
35
36app.use(express.json());
37app.use(express.urlencoded({ extended: false }));
38app.use(cookieParser());
39app.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}));
45app.use(express.static(path.join(__dirname, 'public')));
46
8d7e2786
BA
47// Before showing any page, check + save credentials
48app.use(function(req, res, next) {
c018b304
BA
49 req.userId = 0; //means "anonymous"
50 res.locals.user = { name: "" }; //"anonymous"
8d7e2786
BA
51 if (!req.cookies.token)
52 return next();
53 UserModel.getOne("sessionToken", req.cookies.token, function(err, user) {
54 if (!!user)
55 {
c018b304 56 req.userId = user.id;
8d7e2786 57 res.locals.user = {
26b8e4f7 58 id: user.id,
8d7e2786
BA
59 name: user.name,
60 email: user.email,
61 notify: user.notify,
62 };
63 }
c018b304
BA
64 else
65 {
66 // Token in cookies presumably wrong: erase it
67 res.clearCookie("token");
68 }
8d7e2786
BA
69 next();
70 });
71});
72
73// Routing
298c42e6
BA
74const routes = require(path.join(__dirname, "routes", "all"));
75app.use('/', routes);
1d184b4c
BA
76
77// catch 404 and forward to error handler
78app.use(function(req, res, next) {
79 next(createError(404));
80});
81
82// error handler
83app.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
92module.exports = app;