-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.babel.js
225 lines (194 loc) · 5.86 KB
/
app.babel.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
/* global __dirname */
/* global process */
"use strict";
import fs from "fs";
import https from "https";
import path from "path";
import express from "express";
import exphbs from "express-handlebars";
import handlebars from "handlebars";
import bodyParser from "body-parser";
import compression from "compression";
import session from "express-session";
// custom helpers
import { handleRender } from "./server/server";
import { requireHttps, requireWww } from "./server/helpers/routing.js";
import { generateXmlSitemap } from "./server/helpers/sitemap.js";
// api imports
import Api from "./service/main";
const API_URL = `${process.env.API_URL}`;
// configuration
const config = {
environment: process.env.NODE_ENV || "development",
isHttps: (!process.env.port && process.env.isHttps === true) || false
};
const app = express();
app.use(compression());
const viewsDir = "./templates";
// setup express to use handlebars as the templating engine
const hbs = exphbs.create({
defaultLayout: "main",
layoutsDir: path.join(__dirname, `${viewsDir}/layouts`),
partialsDir: path.join(__dirname, `${viewsDir}/partials`),
extname: ".hbs"
});
// allows partials to be organised in subfolders
hbs
.getTemplates(path.join(__dirname, `${viewsDir}/partials`))
.then(function(partials) {
for (let partial in partials) {
handlebars.registerPartial(partial, "{{" + partial + "}}");
}
})
.catch(error => {
console.log(`Unable to retrieve templates. Error: ${error}`);
});
app.set("views", path.join(__dirname, `${viewsDir}`));
app.engine("hbs", hbs.engine);
app.set("view engine", "hbs");
// preload webfonts
app.use("/fonts", (req, res, next) => {
const protocol = req.get("x-arr-ssl") ? req.protocol + "s" : req.protocol;
// https://coderead.wordpress.com/2014/09/05/redirecting-to-https-in-node-js-on-azure-websites/
res.set(
"Link",
`${protocol +
"://" +
req.get("host") +
req.originalUrl}; rel=preload; as=style`
);
next();
});
// setup server for static assets
app.use(
"/",
express.static(path.join(__dirname, "dist"), { maxAge: 604800000 })
);
//if request url matches /media/* then redirect to API_URL/media/*
app.use((req, res, next) => {
if (/\/media\/[^\/]+/.test(req.url)) {
return res.redirect(API_URL.concat(req.url));
}
next();
});
// https://medium.com/@yash.kulshrestha/using-lets-encrypt-with-express-e069c7abe625
app.use("/.well-known", express.static(path.join(__dirname, ".well-known")));
app.use("/sitemap.xml", (req, res) => {
generateXmlSitemap(req, res).then(response => {
res.header("Content-Type", "text/xml");
res.send(response);
});
});
// require HTTPS
app.use(requireHttps);
// redirect to include www
app.use(requireWww);
// Setup body parser for parsing POST request bodies
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
const sessionExpiration = 20 * 60 * 1000; // 20 * 60 seconds * 1000ms
// Setup session middleware
app.use(
session({
secret: "test",
cookie: { maxAge: sessionExpiration },
unset: "destroy",
resave: true,
saveUninitialized: false,
sameSite: true
})
);
// Middleware for the creation of session variables
app.use((req, res, next) => {
if (!req.session.messages) {
req.session.messages = [];
}
if (!req.session.formValues) {
req.session.formValues = {};
}
next();
});
// Path validation middleware
app.use((req, res, next) => {
// Get the URL path only from the whole URL
const urlPath = Api.router.extractUrlPath(req.path);
Api.router
.isValidPath(urlPath)
.then(valid => {
// If the request is valid, then continue on
if (valid) {
next();
return;
}
console.log(`${urlPath} is not a valid path, checking for exceptions`);
// If they are not trying to get html, return a 404
if (!req.headers.accept || !req.headers.accept.includes("html")) {
// Return just a 404
console.log(`${urlPath} does not accept HTML`);
res.status(404).send();
return;
}
// Check against the exceptions to see if this urlPath matches an exception
const exceptions = [];
for (let i = exceptions.length - 1; i >= 0; i--) {
const isException = urlPath.match(new RegExp(exceptions[i]));
if (isException) {
console.log(`${urlPath} is an exception, not showing 404`);
next();
return;
}
}
// Otherwise, pass a flag with the request for the 404 page to be rendered
console.log(`${urlPath} is not an exception, showing 404`);
req.show404 = true;
next();
return;
})
.catch(error => {
console.error(`Unable to retrieve routing table: ${error}`);
req.show500 = true;
next();
});
});
// React-Redux middleware
app.use(handleRender);
app.use(function(error, req, res, next) {
console.error(error.message);
if (config.environment === "development") {
throw error;
} else {
res.status(500);
res.render("500", { layout: false });
}
return;
});
// use the environment's port or a random port
const port =
process.env.port ||
(process.env.isDev
? 3000
: Math.floor(Math.random() * (65535 - 1024)) + 1024);
app.listen(port, () => {
console.log(`Running ${config.environment} on localhost:${port}`);
});
if (config.isHttps) {
const options = {
key: fs.readFileSync("server.key"),
cert: fs.readFileSync("server.crt"),
requestCert: false,
rejectUnauthorized: false
};
// create a different random port for HTTPS
let httpsPort = process.env.isDev
? 6001
: Math.floor(Math.random() * 65535) + 1024;
while (httpsPort === port) {
httpsPort = Math.floor(Math.random() * 65535) + 1024;
}
const server = https.createServer(options, app).listen(httpsPort, () => {
console.log(
`Running ${config.environment} (HTTPS) on localhost:${httpsPort}`
);
});
}
module.exports = app;