-
Notifications
You must be signed in to change notification settings - Fork 976
Expand file tree
/
Copy pathapp.ts
More file actions
234 lines (193 loc) · 6.67 KB
/
app.ts
File metadata and controls
234 lines (193 loc) · 6.67 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
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
import express = require('express')
import path = require('path')
import favicon = require('serve-favicon')
import loggerMorgan = require('morgan')
import cookieParser = require('cookie-parser')
import bodyParser = require('body-parser')
import httpProxyImport = require('http-proxy')
import * as http from 'http'
import ApiStatusCodes from './api/ApiStatusCodes'
import BaseApi from './api/BaseApi'
import InjectionExtractor from './injection/InjectionExtractor'
import * as Injector from './injection/Injector'
import DownloadRouter from './routes/download/DownloadRouter'
import LoginRouter from './routes/login/LoginRouter'
import UserRouter from './routes/user/UserRouter'
import CaptainManager from './user/system/CaptainManager'
import CaptainConstants from './utils/CaptainConstants'
import Logger from './utils/Logger'
import Utils from './utils/Utils'
// import { NextFunction, Request, Response } from 'express'
const httpProxy = httpProxyImport.createProxyServer({})
const app = express()
app.set('views', path.join(__dirname, '../views'))
app.set('view engine', 'ejs')
app.use(favicon(path.join(__dirname, '../public', 'favicon.ico')))
app.use(
loggerMorgan('dev', {
skip: function (req, res) {
return (
req.originalUrl === CaptainConstants.healthCheckEndPoint ||
req.originalUrl.startsWith(
CaptainConstants.netDataRelativePath + '/'
)
)
},
})
)
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: false,
})
)
app.use(cookieParser())
if (CaptainConstants.isDebug) {
app.use('*', function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Credentials', 'true')
res.setHeader(
'Access-Control-Allow-Headers',
`${CaptainConstants.headerNamespace},${CaptainConstants.headerAuth},Content-Type`
)
if (req.method === 'OPTIONS') {
res.sendStatus(200)
} else {
next()
}
})
app.use('/force-exit', function (req, res, next) {
res.send('Okay... I will exit in a second...')
setTimeout(function () {
process.exit(0)
}, 500)
})
}
app.use(Injector.injectGlobal())
app.use(function (req, res, next) {
if (InjectionExtractor.extractGlobalsFromInjected(res).forceSsl) {
const isRequestSsl =
req.secure || req.get('X-Forwarded-Proto') === 'https'
if (!isRequestSsl) {
const newUrl = `https://${req.get('host')}${req.originalUrl}`
res.redirect(302, newUrl)
return
}
}
next()
})
app.use(express.static(path.join(__dirname, '../dist-frontend')))
app.use(express.static(path.join(__dirname, 'public')))
app.use(CaptainConstants.healthCheckEndPoint, function (req, res, next) {
res.send(CaptainManager.get().getHealthCheckUuid())
})
// ************ Beginning of reverse proxy 3rd party services ****************************************
app.use(CaptainConstants.netDataRelativePath, function (req, res, next) {
if (
req.originalUrl.indexOf(CaptainConstants.netDataRelativePath + '/') !==
0
) {
const isRequestSsl =
req.secure || req.get('X-Forwarded-Proto') === 'https'
const newUrl =
(isRequestSsl ? 'https://' : 'http://') +
req.get('host') +
CaptainConstants.netDataRelativePath +
'/'
res.redirect(302, newUrl)
return
}
next()
})
app.use(
CaptainConstants.netDataRelativePath,
Injector.injectUserUsingCookieDataOnly()
)
app.use(CaptainConstants.netDataRelativePath, function (req, res, next) {
if (!InjectionExtractor.extractUserFromInjected(res)) {
Logger.e('User not logged in for NetData')
res.sendStatus(500)
} else {
next()
}
})
httpProxy.on('error', function (err, req, resOriginal: http.ServerResponse) {
if (err) {
Logger.e(err)
}
resOriginal.writeHead(500, {
'Content-Type': 'text/plain',
})
if (
(err + '').indexOf('getaddrinfo ENOTFOUND captain-netdata-container') >=
0
) {
resOriginal.end(
`Something went wrong... err: \n NetData is not running! Are you sure you have started it?`
)
} else {
resOriginal.end(`Something went wrong... err: \n ${err ? err : 'NULL'}`)
}
})
app.use(CaptainConstants.netDataRelativePath, function (req, res, next) {
if (Utils.isNotGetRequest(req)) {
res.writeHead(401, {
'Content-Type': 'text/plain',
})
res.send('Demo mode is for viewing only')
return
}
httpProxy.web(req, res, {
target: `http://${CaptainConstants.netDataContainerName}:19999`,
})
})
// ************ End of reverse proxy 3rd party services ****************************************
// ********************* Beginning of API End Points *******************************************
const API_PREFIX = '/api/'
app.use(API_PREFIX + ':apiVersionFromRequest/', function (req, res, next) {
if (req.params.apiVersionFromRequest !== CaptainConstants.apiVersion) {
res.send(
new BaseApi(
ApiStatusCodes.STATUS_ERROR_GENERIC,
`This captain instance only accepts API ${CaptainConstants.apiVersion}`
)
)
return
}
if (!InjectionExtractor.extractGlobalsFromInjected(res).initialized) {
const response = new BaseApi(
ApiStatusCodes.STATUS_ERROR_CAPTAIN_NOT_INITIALIZED,
'Captain is not ready yet...'
)
res.send(response)
return
}
next()
})
// unsecured end points:
app.use(API_PREFIX + CaptainConstants.apiVersion + '/login/', LoginRouter)
app.use(
API_PREFIX + CaptainConstants.apiVersion + '/downloads/',
DownloadRouter
)
// secured end points
app.use(API_PREFIX + CaptainConstants.apiVersion + '/user/', UserRouter)
// ********************* End of API End Points *******************************************
// catch 404 and forward to error handler
app.use(function (req, res, next) {
res.locals.err = new Error('Not Found')
res.locals.err.errorStatus = 404
next(res.locals.err)
})
// error handler
app.use(function (err, req, res, next) {
Promise.reject(err).catch(ApiStatusCodes.createCatcher(res))
} as express.ErrorRequestHandler)
export default app
export function initializeCaptainWithDelay() {
// Initializing with delay helps with debugging. Usually, docker didn't see the CAPTAIN service
// if this was done without a delay
setTimeout(function () {
CaptainManager.get().initialize()
}, 1500)
}