-
Notifications
You must be signed in to change notification settings - Fork 295
/
app.js
78 lines (63 loc) · 2.18 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
require('dotenv').config({
path: `./env-files/${process.env.NODE_ENV || 'development'}.env`,
});
const express = require('express');
const path = require('path');
const expressLayouts = require('express-ejs-layouts');
const cookieParser = require('cookie-parser');
const session = require('express-session');
const RedisStore = require('connect-redis')(session);
const initAuthMiddleware = require('./features/login/init-auth-middleware');
const indexRouter = require('./routes/index');
const redisStoreConfig = {
host: process.env.REDIS_HOST,
port: process.env.REDIS_PORT,
};
if (process.env.REDIS_URL) {
redisStoreConfig.url = process.env.REDIS_URL; // this will use the REDIS_URL required for logging into the Redis addon provided by Heroku
}
if (process.env.REDIS_PASSWORD) {
redisStoreConfig.password = process.env.REDIS_PASSWORD; // this will use the REDIS_PASSWORD if required
}
const redisStore = new RedisStore(redisStoreConfig);
const staticFolder = process.env.NODE_ENV === 'development' ? 'public' : 'dist';
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(expressLayouts);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, staticFolder)));
const { COOKIE_EXPIRATION_MS } = process.env;
app.use(
session({
store: redisStore,
secret: 'keyboard cat',
name: process.env.SESSION_COOKIE_NAME,
resave: false,
saveUninitialized: true,
cookie: {
secure: process.env.NODE_ENV === 'production',
expires: Date.now() + parseInt(COOKIE_EXPIRATION_MS, 10),
maxAge: parseInt(COOKIE_EXPIRATION_MS, 10),
},
})
);
initAuthMiddleware(app);
// Middleware used for setting error and success messages as available in _ejs_ templates
app.use((req, res, next) => {
if (req.session) {
res.locals.messages = req.session.messages;
res.locals.userInfo = req.session.userInfo;
req.session.messages = {};
}
next();
});
app.use('/', indexRouter);
// catch 404 and forward to error handler
app.use((req, res) => {
res.status(404).render('pages/404');
});
module.exports = app;