-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.js
168 lines (141 loc) · 4.78 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
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
const createError = require("http-errors");
const favicon = require("serve-favicon");
const express = require("express");
const path = require("path");
const cookieParser = require("cookie-parser");
const morgan = require("morgan");
const session = require("express-session");
const passport = require("passport");
const Knex = require("knex");
const pg = require("pg");
const Model = require("objection").Model;
const redis = require("redis");
const RedisStore = require("connect-redis").default;
const csrf = require("csurf");
const compression = require("compression");
const methodOverride = require("method-override");
const httpsRedirect = require("express-https-redirect");
const webpack = require("webpack");
const { parse } = require("pg-connection-string");
// Following packages are not required in production and importing them
// will throw an error if devDependencies are not installed
const isProd = process.env.NODE_ENV === "production";
const webpackConfig = isProd ? null : require("./webpack.dev.config");
const compiler = isProd ? null : webpack(webpackConfig);
const { initializeI18n } = require("./utils/i18n");
const csrfProtection = csrf({ cookie: true });
const staticify = require("staticify")(path.join(__dirname, "public"));
const { setupLocals } = require("./utils/ServerUtils");
const setupPassport = require("./passport");
const setupRoutes = require("./routes");
const logger = require("./logger");
pg.defaults.ssl = isProd;
const knex = Knex({
client: "pg",
connection: {
...parse(process.env.DATABASE_URL),
ssl: { rejectUnauthorized: false },
},
});
Model.knex(knex);
const app = express();
setupPassport(passport);
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
// Strip staticify hash before webpack-dev-middleware, otherwise it won't
// recognize hashed files
app.use((req, res, next) => {
req.url = staticify.stripVersion(req.url);
next();
});
if (!isProd && process.env.WEBPACK_HOT_RELOAD) {
logger.info("Webpack building frontend... Watch and hot reload enabled.");
app.use(
require("webpack-dev-middleware")(compiler, {
publicPath: webpackConfig.output.publicPath,
}),
);
app.use(require("webpack-hot-middleware")(compiler));
} else {
logger.info("Frontend build step skipped, using existing build");
}
app.disable("x-powered-by");
app.use(compression());
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(morgan("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(methodOverride("_method"));
// i18n initialization must be early to have t, languages etc. set when
// rendering error page if e.g. csrf fails
initializeI18n(app);
app.use(csrfProtection);
// Initialize redis client
const redisUrl = process.env.REDIS_URL;
const redisClient = redis.createClient({
url: redisUrl,
socket: {
tls: redisUrl.match(/rediss:/) != null,
rejectUnauthorized: false,
},
});
redisClient.on("error", (error) => {
logger.error(`Redis client error`, error);
});
redisClient.connect().catch((err) => logger.error(err));
// Initialize redis store
const redisStore = new RedisStore({ client: redisClient });
// Initialize sesssion storage.
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
store: redisStore,
}),
);
app.use(staticify.middleware);
app.use(express.static(path.join(__dirname, "public")));
app.use("/", httpsRedirect());
app.use(passport.initialize());
app.use(passport.session());
app.use((req, res, next) => {
// Add language to session for correct redirect after login
// conditional required, otherwise value overwritten with 'fi' after login
if (!req.user && req.path !== "/profiili/callback")
req.session.languageRedirect = "/" + req.language;
// Add locals for rendering pug views
res.locals.user = req.user;
res.locals.pageUrl = process.env.HOME_URL + req.originalUrl;
res.locals.env = process.env;
res.locals.pathWithoutLanguage = req.url;
next();
});
setupLocals(app, staticify.getVersionedPath);
setupRoutes(app);
app.use(function (req, res, next) {
next(createError(404));
});
app.use(function (err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
if (err.status !== 404) {
logger.warn("Express error handler", { err });
}
res.status(err.status || 500);
// Handle errors for ajax requests (provide error in JSON instead of html)
if (req.get("Accept") === "application/json") {
res.json({
message: err.message,
// Provide error also in express-validator format so it will be shown to user
errors: [{ msg: err.message }],
});
return;
}
res.render("error", {
user: req.user,
env: process.env,
});
});
module.exports = app;