-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp.ts
More file actions
179 lines (161 loc) · 5.36 KB
/
app.ts
File metadata and controls
179 lines (161 loc) · 5.36 KB
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
/* eslint-disable @typescript-eslint/no-var-requires */
import path from 'path'
import * as http from 'http'
import cors from 'cors'
import express from 'express'
import Routes from './constants/routes'
import * as nunjucks from 'nunjucks'
import bodyParser from 'body-parser'
import sessionStore, { SessionStore } from './services/sessionStore'
import { getUserProfile } from './services/signon'
import OAuth2Strategy from 'passport-oauth2'
import passport from 'passport'
import session from 'express-session'
import { generateSessionId } from './utils/auth'
import config from './config'
import { pageNotFound } from './middleware/pageNotFound'
import { errorMiddleware } from './middleware/errorMiddleware'
import { allowGoogleAnalytics } from './middleware/allowGoogleAnalytics'
import { showCookieMessage } from './middleware/showCookieMessage'
import { hideFeedbackSurvey } from './middleware/hideFeedbackSurvey'
import { requestRateLimiter } from './middleware/requestRateLimit'
import log, { httpLogger } from './utils/logging'
import cookieParser from 'cookie-parser'
class App {
public app: express.Express = express()
public port: string | number
constructor(routes: Routes[]) {
this.app = express()
this.port = config.port
/*
'trust proxy' must be set to 2 when deployed behind GCP load-balancing in order to correctly identify
the requestor's IP address rather than that of the load-balancer. This is required for per-user rate-limiting.
See also - https://cloud.google.com/load-balancing/docs/https#x-forwarded-for_header
*/
this.app.set('trust proxy', 2)
this.initializeMiddlewares()
this.initializeRoutes(routes)
this.initializeRenderEngine()
this.initializeFinalMiddlewares()
}
public listen(): void {
const server = http.createServer(this.app)
server.keepAliveTimeout = 1000 * (60 * 6) // 6 minutes
server.listen(this.port, () => {
log.info(`🚀 App listening on the port ${this.port}`)
})
const handleShutdown = () => {
if (config.authEnabled) {
const { getClient } = require('.services/redis')
getClient().disconnect()
}
server.close(() => {
log.info('Server gracefully shut down')
process.exit(0)
})
}
process.on('SIGINT', handleShutdown)
process.on('SIGTERM', handleShutdown)
}
public getServer(): express.Application {
return this.app
}
private initializeMiddlewares() {
if (config.enableHMR) {
const {
devMiddleware,
hotMiddleware,
} = require('./middleware/webpack-hot-module-replacement')
this.app.use(devMiddleware())
this.app.use(hotMiddleware())
}
this.app.use(cookieParser())
this.app.use(cors())
this.app.use(express.static('./public'))
this.app.use(bodyParser.urlencoded({ extended: true }))
this.app.use(bodyParser.json())
this.app.use(allowGoogleAnalytics)
this.app.use(showCookieMessage)
this.app.use(hideFeedbackSurvey)
this.app.use(requestRateLimiter)
this.initializeLogin()
this.app.use(httpLogger)
}
private initializeRoutes(routes: Routes[]) {
routes.forEach((route) => {
this.app.use('/', route.router)
})
}
private initializeRenderEngine() {
const views = [
path.join(__dirname, '../../node_modules/govuk-frontend/dist'),
path.join(__dirname, './views'),
]
nunjucks.configure(views, {
autoescape: true,
express: this.app,
})
this.app.engine('html', nunjucks.render)
this.app.set('views', views)
this.app.set('view engine', 'html')
}
private initializeLogin() {
if (!config.authEnabled) {
log.debug('Auth is disabled')
return
}
log.debug('Auth is enabled')
passport.serializeUser((user: any, done: any) => done(null, user))
passport.deserializeUser((user: any, done: any) => done(null, user))
this.app.use(
session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false,
cookie: { secure: !(config.environment === 'local') },
store: (sessionStore as SessionStore).getStore(),
genid: generateSessionId,
})
)
this.app.use(passport.initialize())
this.app.use(passport.session())
passport.use(
new OAuth2Strategy(
{
authorizationURL: config.oauthAuthUrl || 'not set',
tokenURL: config.oauthTokenUrl || 'not set',
clientID: config.clientId || 'not set',
clientSecret: config.clientSecret || 'not set',
callbackURL: config.oauthCallbackUrl || 'not set',
},
async function (
accessToken: string,
refreshToken: string,
profile: any,
doneCallback: any
) {
let profileData
try {
log.debug('Fetching user profile')
profileData = await getUserProfile(accessToken)
} catch (error) {
log.error({ error }, 'ERROR fetching user data')
return doneCallback(error)
}
const userSessionData = {
profileData,
refreshToken,
accessToken,
}
log.debug({ userSessionData }, 'User data fetched successfully')
doneCallback(null, userSessionData)
}
)
)
}
private initializeFinalMiddlewares() {
this.app.use(pageNotFound)
this.app.use(errorMiddleware)
}
}
export default App