forked from alphagov/verify-local-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
298 lines (245 loc) · 8.4 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
var path = require('path')
var express = require('express')
var session = require('express-session')
var nunjucks = require('nunjucks')
var routes = require('./app/routes.js')
var documentationRoutes = require('./docs/documentation_routes.js')
var favicon = require('serve-favicon')
var app = express()
var documentationApp = express()
var bodyParser = require('body-parser')
var browserSync = require('browser-sync')
var config = require('./app/config.js')
var utils = require('./lib/utils.js')
var packageJson = require('./package.json')
var councilsData = require('./app/councils.json')
// Grab environment variables specified in Procfile or as Heroku config vars
var releaseVersion = packageJson.version
var username = process.env.USERNAME
var password = process.env.PASSWORD
var env = process.env.NODE_ENV || 'development'
var useAuth = process.env.USE_AUTH || config.useAuth
var useHttps = process.env.USE_HTTPS || config.useHttps
var analyticsId = process.env.ANALYTICS_TRACKING_ID
var useAutoStoreData = process.env.USE_AUTOSTOREDATA || config.useAutoStoreData
app.locals.useAutoStoreData = (useAutoStoreData === 'true')
env = env.toLowerCase()
useAuth = useAuth.toLowerCase()
useHttps = useHttps.toLowerCase()
var useDocumentation = (config.useDocumentation === 'true')
// Promo mode redirects the root to /docs - so our landing page is docs when published on heroku
var promoMode = process.env.PROMO_MODE || 'false'
promoMode = promoMode.toLowerCase()
// Disable promo mode if docs aren't enabled
if (!useDocumentation) promoMode = 'false'
// Authenticate against the environment-provided credentials, if running
// the app in production (Heroku, effectively)
if (env === 'production' && useAuth === 'true') {
app.use(utils.basicAuth(username, password))
}
// Set up App
var appViews = [path.join(__dirname, '/app/views/'), path.join(__dirname, '/lib/')]
var nunjucksAppEnv = nunjucks.configure(appViews, {
autoescape: true,
express: app,
noCache: true,
watch: true
})
// Nunjucks filters
utils.addNunjucksFilters(nunjucksAppEnv)
// Set views engine
app.set('view engine', 'html')
// Middleware to serve static assets
app.use('/public', express.static(path.join(__dirname, '/public')))
app.use('/public', express.static(path.join(__dirname, '/govuk_modules/govuk_template/assets')))
app.use('/public', express.static(path.join(__dirname, '/govuk_modules/govuk_frontend_toolkit')))
app.use('/public/images/icons', express.static(path.join(__dirname, '/govuk_modules/govuk_frontend_toolkit/images')))
// Elements refers to icon folder instead of images folder
app.use(favicon(path.join(__dirname, 'govuk_modules', 'govuk_template', 'assets', 'images', 'favicon.ico')))
// Set up documentation app
if (useDocumentation) {
var documentationViews = [path.join(__dirname, '/docs/views/'), path.join(__dirname, '/lib/')]
var nunjucksDocumentationEnv = nunjucks.configure(documentationViews, {
autoescape: true,
express: documentationApp,
noCache: true,
watch: true
})
// Nunjucks filters
utils.addNunjucksFilters(nunjucksDocumentationEnv)
// Set views engine
documentationApp.set('view engine', 'html')
}
// Support for parsing data in POSTs
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
// Support session data
app.use(session({
resave: false,
saveUninitialized: false,
secret: Math.round(Math.random() * 100000).toString(),
}))
// send assetPath to all views
app.use(function (req, res, next) {
res.locals.asset_path = '/public/'
var councils = councilsData
res.locals.councils = councils
next()
})
console.log({'autodata': useAutoStoreData})
if (useAutoStoreData === 'true') {
app.use(utils.autoStoreData)
app.use(function (req, res, next) {
// add nunjucks function to get values, needs to be here as they need access to req.session
nunjucksAppEnv.addGlobal('checked', function (name, value) {
if (req.session.data === undefined) {
return ''
}
var storedValue = req.session.data[name]
if (storedValue === undefined) {
return ''
}
if (Array.isArray(storedValue)) {
var inArray = storedValue.indexOf(value) !== -1
return inArray ? 'checked' : ''
} else {
return value === storedValue ? 'checked' : ''
}
})
// set council variable to all of relevant councilData
if(req.session.data.councilChoice){
for(var i in councilsData){
if(councilsData[i].string == req.session.data.councilChoice){
req.session.data.council = councilsData[i]
}
}
}else{
req.session.data.council = councilsData[0]
}
next()
})
documentationApp.use(utils.autoStoreData)
documentationApp.use(function (req, res, next) {
// add nunjucks function to get values, needs to be here as they need access to req.session
nunjucksDocumentationEnv.addGlobal('checked', function (name, value) {
if (req.session.data === undefined) {
return ''
}
var storedValue = req.session.data[name]
if (storedValue === undefined) {
return ''
}
if (Array.isArray(storedValue)) {
var inArray = storedValue.indexOf(value) !== -1
return inArray ? 'checked' : ''
} else {
return value === storedValue ? 'checked' : ''
}
})
next()
})
}
// Add variables that are available in all views
app.use(function (req, res, next) {
res.locals.analyticsId = analyticsId
res.locals.serviceName = config.serviceName
res.locals.cookieText = config.cookieText
res.locals.releaseVersion = 'v' + releaseVersion
res.locals.promoMode = promoMode
next()
})
// Force HTTPs on production connections
if (env === 'production' && useHttps === 'true') {
app.use(utils.forceHttps)
}
// Disallow search index idexing
app.use(function (req, res, next) {
// Setting headers stops pages being indexed even if indexed pages link to them.
res.setHeader('X-Robots-Tag', 'noindex')
next()
})
app.get('/prototype-admin/clear-data', function (req, res) {
req.session.destroy()
res.render('prototype-admin/clear-data')
})
app.get('/robots.txt', function (req, res) {
res.type('text/plain')
res.send('User-agent: *\nDisallow: /')
})
// Redirect root to /docs when in promo mode.
if (promoMode === 'true') {
console.log('Prototype kit running in promo mode')
app.get('/', function (req, res) {
res.redirect('/docs')
})
}
// routes (found in app/routes.js)
if (typeof (routes) !== 'function') {
console.log(routes.bind)
console.log('Warning: the use of bind in routes is deprecated - please check the prototype kit documentation for writing routes.')
routes.bind(app)
} else {
app.use('/', routes)
}
// Returns a url to the zip of the latest release on github
app.get('/prototype-admin/download-latest', function (req, res) {
var url = utils.getLatestRelease()
res.redirect(url)
})
if (useDocumentation) {
// Create separate router for docs
app.use('/docs', documentationApp)
// Docs under the /docs namespace
documentationApp.use('/', documentationRoutes)
}
// Strip .html and .htm if provided
app.get(/\.html?$/i, function (req, res) {
var path = req.path
var parts = path.split('.')
parts.pop()
path = parts.join('.')
res.redirect(path)
})
// Auto render any view that exists
// App folder routes get priority
app.get(/^\/([^.]+)$/, function (req, res) {
utils.matchRoutes(req, res)
})
if (useDocumentation) {
// Documentation routes
documentationApp.get(/^\/([^.]+)$/, function (req, res) {
if (!utils.matchMdRoutes(req, res)) {
utils.matchRoutes(req, res)
}
})
}
// redirect all POSTs to GETs - this allows users to use POST for autoStoreData
app.post(/^\/([^.]+)$/, function (req, res) {
res.redirect('/' + req.params[0])
})
console.log('\nGOV.UK Prototype kit v' + releaseVersion)
// Display warning not to use kit for production services.
console.log('\nNOTICE: the kit is for building prototypes, do not use it for production services.')
// start the app
utils.findAvailablePort(app, function (port) {
console.log('Listening on port ' + port + ' url: http://localhost:' + port)
if (env === 'production') {
app.listen(port)
} else {
app.listen(port - 50, function () {
browserSync({
proxy: 'localhost:' + (port - 50),
port: port,
ui: false,
files: ['public/**/*.*', 'app/views/**/*.*'],
ghostmode: false,
open: false,
notify: false,
logLevel: 'error'
})
})
}
})
module.exports = app