forked from alphagov/govuk-prototype-kit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
220 lines (182 loc) · 6.55 KB
/
server.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
// core dependencies
const fsp = require('fs').promises
const path = require('path')
const url = require('url')
// npm dependencies
const bodyParser = require('body-parser')
const cookieParser = require('cookie-parser')
const dotenv = require('dotenv')
const express = require('express')
const { expressNunjucks, getNunjucksAppEnv, stopWatchingNunjucks } = require('./lib/nunjucks/nunjucksConfiguration')
// We want users to be able to keep api keys, config variables and other
// envvars in a `.env` file, run dotenv before other code to make sure those
// variables are available
dotenv.config()
// Local dependencies
const { projectDir, packageDir, appViewsDir, finalBackupNunjucksDir } = require('./lib/utils/paths')
const config = require('./lib/config.js').getConfig()
const packageJson = require('./package.json')
const { govukFrontendPaths } = require('./lib/govukFrontendPaths')
const utils = require('./lib/utils')
const sessionUtils = require('./lib/session.js')
const plugins = require('./lib/plugins/plugins.js')
const routesApi = require('./lib/routes/api.js')
const app = express()
routesApi.setApp(app)
// Set up configuration variables
const releaseVersion = packageJson.version
// Force HTTPS on production. Do this before using basicAuth to avoid
// asking for username/password twice (for `http`, then `https`).
const isSecure = (config.isProduction && config.useHttps)
if (isSecure) {
app.use(utils.forceHttps)
app.set('trust proxy', 1) // needed for secure cookies on heroku
}
// Find GOV.UK Frontend (via project, internal package fallback)
const govukFrontend = govukFrontendPaths([projectDir, packageDir])
// Find GOV.UK Frontend (via internal package, project fallback)
const govukFrontendInternal = govukFrontendPaths([packageDir, projectDir])
// Add variables that are available in all views
app.locals.asset_path = '/public/'
app.locals.useAutoStoreData = config.useAutoStoreData
app.locals.releaseVersion = 'v' + releaseVersion
app.locals.serviceName = config.serviceName
app.locals.GOVUKPrototypeKit = {
isProduction: config.isProduction,
isDevelopment: config.isDevelopment
}
if (plugins.legacyGovukFrontendFixesNeeded()) {
app.locals.GOVUKPrototypeKit.legacyGovukFrontendFixesNeeded = true
}
// pluginConfig sets up variables used to add the scripts and stylesheets to each page.
app.locals.pluginConfig = plugins.getAppConfig({
scripts: utils.prototypeAppScripts
})
// Add GOV.UK Frontend paths to Nunjucks locals
app.locals.govukFrontend = govukFrontend
app.locals.govukFrontendInternal = govukFrontendInternal
// keep extensionConfig around for backwards compatibility
// TODO: remove in v14
app.locals.extensionConfig = app.locals.pluginConfig
// Support session data storage
app.use(sessionUtils.getSessionMiddleware())
// use cookie middleware for reading authentication cookie
app.use(cookieParser())
// Authentication middleware must be loaded before other middleware such as
// static assets to prevent unauthorised access
app.use(require('./lib/authentication.js')())
const nunjucksConfig = {
autoescape: true,
noCache: true,
watch: false // We are now setting this to `false` (it's by default false anyway) as having it set to `true` for production was making the tests hang
}
if (config.isDevelopment) {
nunjucksConfig.watch = true
}
nunjucksConfig.express = app
// Finds GOV.UK Frontend via `getAppViews()` only if installed
// but uses the internal package as a backup if uninstalled
const nunjucksAppEnv = getNunjucksAppEnv(
plugins.getAppViews([appViewsDir, finalBackupNunjucksDir]),
govukFrontendInternal
)
expressNunjucks(nunjucksAppEnv, app)
// Add Nunjucks filters
utils.addNunjucksFilters(nunjucksAppEnv)
// Add Nunjucks functions
utils.addNunjucksFunctions(nunjucksAppEnv)
// Set views engine
app.set('view engine', 'njk')
// Middleware to serve static assets
app.use('/public', express.static(path.join(projectDir, '.tmp', 'public')))
app.use('/public', express.static(path.join(projectDir, 'app', 'assets')))
// Support for parsing data in POSTs
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
// Automatically store all data users enter
if (config.useAutoStoreData) {
app.use(sessionUtils.autoStoreData)
sessionUtils.addCheckedFunction(nunjucksAppEnv)
}
// Prevent search indexing
app.use((req, res, next) => {
// Setting headers stops pages being indexed even if indexed pages link to them.
res.setHeader('X-Robots-Tag', 'noindex')
next()
})
require('./lib/manage-prototype-routes.js')
require('./lib/plugins/plugins-routes.js')
const { getErrorModel } = require('./lib/utils/errorModel')
utils.addRouters(app)
// Strip .html, .htm and .njk if provided
app.get(/\.(html|htm|njk)$/i, (req, res) => {
let path = req.path
const parts = path.split('.')
parts.pop()
path = parts.join('.')
res.redirect(path)
})
// Auto render any view that exists
// App folder routes get priority
app.get(/^([^.]+)$/, async (req, res, next) => {
await utils.matchRoutes(req, res, next)
})
// Redirect all POSTs to GETs - this allows users to use POST for autoStoreData
app.post(/^\/([^.]+)$/, (req, res) => {
res.redirect(url.format({
pathname: '/' + req.params[0],
query: req.query
})
)
})
// redirect old local docs to the docs site
app.get('/docs/tutorials-and-examples', (req, res) => {
res.redirect('https://prototype-kit.service.gov.uk/docs')
})
app.get('/', async (req, res) => {
const starterHomepageCode = await fsp.readFile(path.join(packageDir, 'prototype-starter', 'app', 'views', 'index.njk'), 'utf8')
res.render('views/backup-homepage', {
starterHomepageCode
})
})
// Catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error(`Page not found: ${decodeURI(req.path)}`)
err.status = 404
next(err)
})
// Display error
// We override the default handler because we want to customise
// how the error appears to users, we want to show a simplified
// message without the stack trace.
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err)
}
if (req.headers['content-type'] && req.headers['content-type'].indexOf('json') !== -1) {
console.error(err.message)
res.status(err.status || 500)
res.send(err.message)
return
}
switch (err.status) {
case 404: {
const path = req.path
res.status(err.status)
res.render('views/error-handling/page-not-found', {
path
})
break
}
default: {
res.status(500)
console.error(err.message)
res.render('views/error-handling/server-error', getErrorModel(err))
break
}
}
})
app.close = stopWatchingNunjucks
module.exports = app