forked from stolostron/grc-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
214 lines (183 loc) · 6.46 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
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
/*******************************************************************************
* Licensed Materials - Property of IBM
* (c) Copyright IBM Corporation 2019. All Rights Reserved.
*
* Note to U.S. Government Users Restricted Rights:
* Use, duplication or disclosure restricted by GSA ADP Schedule
* Contract with IBM Corp.
*******************************************************************************/
/* Copyright (c) 2020 Red Hat, Inc. */
/* Copyright Contributors to the Open Cluster Management project */
'use strict'
const log4js = require('log4js'),
logger = log4js.getLogger('server'),
mime = require('mime-types'),
fs = require('fs'),
helmet = require('helmet')
const cacheControlStr = 'Cache-Control'
const acmAccessTokenCookieStr = 'acm-access-token-cookie'
const xContentTypeOptions = 'X-Content-Type-Options'
const log4jsConfig = process.env.LOG4JS_CONFIG ? JSON.parse(process.env.LOG4JS_CONFIG) : undefined
log4js.configure(log4jsConfig || './server/config/log4js.json')
logger.info(`[pid ${process.pid}] [env ${process.env.NODE_ENV}] started.`)
const express = require('express'),
exphbs = require('express-handlebars'),
handlebarsHelpers = require('./server/lib/server/handlebarsHelpers'),
path = require('path'),
appConfig = require('./server/config'),
appUtil = require('./server/lib/server/app-util')
//early initialization
require('node-i18n-util')
process.env.BABEL_ENV = 'server'
require('@babel/register')
require('ignore-styles')
const bodyParser = require('body-parser'),
cookieParser = require('cookie-parser'),
csurf = require('csurf'),
requestLogger = require('./server/middleware/request-logger'),
controllers = require('./server/controllers')
const app = express()
app.use(helmet({ // in production these headers are set by management-ingress
contentSecurityPolicy: false,// https://github.com/helmetjs/helmet/wiki/Helmet-4-upgrade-guide
frameguard: false
}))
// Remove the X-Powered-By headers.
app.disable('x-powered-by')
const morgan = require('morgan')
if (process.env.NODE_ENV === 'production') {
app.use(
'*',
morgan('combined', {
skip: (req, res) => res.statusCode < 400,
}),
)
} else {
app.use('*', morgan('dev'))
}
const csrfMiddleware = csurf({
cookie: {
httpOnly: false,
secure: true
}
})
function setRes(res) {
res.setHeader(cacheControlStr, 'no-store')
res.setHeader('Pragma', 'no-cache')
return res
}
function setReq(req) {
const accessToken = req.cookies[acmAccessTokenCookieStr]
if (req.headers.authorization) {
req.headers.authorization = `Bearer ${accessToken}`
}
else {
req.headers.Authorization = `Bearer ${accessToken}`
}
return req
}
const { createProxyMiddleware } = require('http-proxy-middleware')
app.use(`${appConfig.get('contextPath')}/graphql`, cookieParser(), csrfMiddleware, (req, res, next) => {
res = setRes(res)
req = setReq(req)
next()
}, createProxyMiddleware({
target: appConfig.get('grcUiApiUrl') || 'https://localhost:4000/grcuiapi',
changeOrigin: true,
pathRewrite: {
[`^${appConfig.get('contextPath')}/graphql`]: '/graphql'
},
secure: false
}))
app.use(`${appConfig.get('contextPath')}/search/graphql`, cookieParser(), csrfMiddleware, (req, res, next) => {
res = setRes(res)
req = setReq(req)
next()
}, createProxyMiddleware({
// TODO - use flag while ironing out the chart changes
target: appConfig.get('searchApiUrl') || 'https://localhost:4010/searchapi',
changeOrigin: true,
pathRewrite: {
[`^${appConfig.get('contextPath')}/search/graphql`]: '/graphql'
},
secure: false
}))
const hbs = exphbs.create({
// Specify helpers which are only registered on this instance.
helpers: {
properties: handlebarsHelpers,
json: function(context) {
return JSON.stringify(context)
}
}
})
app.engine('handlebars', hbs.engine)
app.set('env', 'production')
app.set('views', `${__dirname}/server/views`)
app.set('view engine', 'handlebars')
app.set('view cache', true)
appUtil.app(app)
const CONTEXT_PATH = appConfig.get('contextPath'),
STATIC_PATH = path.join(__dirname, 'public')
app.use(cookieParser(), csrfMiddleware, (req, res, next) => {
if(!req.path.endsWith('.js') && !req.path.endsWith('.css')) {
next()
return
}
res.append('Content-Encoding', 'gzip')
const type = mime.lookup(path.join('public', req.path))
if (typeof type !== 'undefined') {
const charset = mime && mime.charsets.lookup(type)
res.append('Content-Type', type + (charset ? `; charset=${charset}` : ''))
}
req.url = `${req.url}.gz`
next()
})
app.use(`${CONTEXT_PATH}`, express.static(STATIC_PATH, {
maxAge: process.env.NODE_ENV === 'development' ? 0 : 1000 * 60 * 60 * 24 * 365,
setHeaders: (res, fp) => {
// set cahce control to 30min, expect for nls
const maxAge = fp.startsWith(`${STATIC_PATH}/nls`) ? 0 : (60 * 60 * 12)
res.setHeader(cacheControlStr, `max-age=${maxAge}`)
res.setHeader(xContentTypeOptions, 'nosniff')
}
}))
app.get(`${CONTEXT_PATH}/performance-now.js.map`, (req, res) => res.sendStatus(404))
app.use(cookieParser())
.use(requestLogger)
.use(bodyParser.json({ limit: '512kb' }))
.use(bodyParser.urlencoded({ extended: false }))
.use(controllers)
app.get('/favicon.ico', (req, res) => res.sendStatus(204))
app.locals.config = require('./server/lib/shared/config')
// this path only existing after npm build
// eslint-disable-next-line import/no-unresolved
app.locals.manifest = require('./public/webpack-assets.json')
let server
if (process.env.NODE_ENV === 'development') {
const https = require('https')
const privateKey = fs.readFileSync('./server/sslcert/server.key', 'utf8')
const certificate = fs.readFileSync('./server/sslcert/server.crt', 'utf8')
const credentials = {key: privateKey, cert: certificate}
server = https.createServer(credentials, app)
} else {
// NOTE: In production, SSL is provided by the ingress
const http = require('http')
server = http.createServer(app)
}
const port = process.env.PORT || appConfig.get('httpPort')
// start server
logger.info('Starting express server.')
server.listen(port, () => {
logger.info(`GRC UI is now running on ${process.env.NODE_ENV === 'development' ? 'https' : 'http'}://localhost:${port}${CONTEXT_PATH}`)
})
process.on('SIGTERM', () => {
logger.info('SIGTERM received. Shutting down express server.')
server.close(err => {
if (err) {
logger.error(err)
process.exit(1)
}
logger.info('Server shutdown successfully.')
process.exit(0)
})
})