forked from openiap/opencore
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebServer.ts
More file actions
210 lines (185 loc) · 9.12 KB
/
Copy pathWebServer.ts
File metadata and controls
210 lines (185 loc) · 9.12 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
import * as path from "path";
import * as winston from "winston";
import * as http from "http";
import * as https from "https";
import * as express from "express";
import * as compression from "compression";
import * as bodyParser from "body-parser";
import * as cookieParser from "cookie-parser";
import * as nodered from "node-red";
import * as morgan from "morgan";
import * as samlauth from "node-red-contrib-auth-saml";
import * as cookieSession from "cookie-session";
import { nodered_settings } from "./nodered_settings";
import { Config } from "./Config";
import { WebSocketClient } from "./WebSocketClient";
import { noderedcontribopenflowstorage } from "./node-red-contrib-openflow-storage";
import { SigninMessage, Message } from "./Message";
import { noderedcontribmiddlewareauth } from "./node-red-contrib-middleware-auth";
import { dashboardAuth } from "./dashboardAuth";
import * as passport from "passport";
export class WebServer {
private static _logger: winston.Logger;
private static app: express.Express = null;
private static settings: nodered_settings = null;
static async configure(logger: winston.Logger, socket: WebSocketClient): Promise<http.Server> {
this._logger = logger;
var options: any = null;
var RED: nodered.Red = nodered;
if (this.app !== null) { return; }
try {
this._logger.debug("WebServer.configure::begin");
if (this.app === null) {
this.app = express();
// this.app.use(morgan('combined', { stream: (winston.stream as any).write }));
var loggerstream = {
write: function (message, encoding) {
logger.silly(message);
}
};
this.app.use(morgan('combined', { stream: loggerstream }));
this.app.use(compression());
this.app.use(bodyParser.urlencoded({ limit: '10mb', extended: true }))
this.app.use(bodyParser.json({ limit: '10mb' }))
this.app.use(cookieParser());
this.app.use("/", express.static(path.join(__dirname, "/public")));
this.app.use(passport.initialize());
this.app.use(passport.session());
passport.serializeUser(async function (user: any, done: any): Promise<void> {
done(null, user);
});
passport.deserializeUser(function (user: any, done: any): void {
done(null, user);
});
var server: http.Server = null;
if (Config.tls_crt != '' && Config.tls_key != '') {
var options: any = {
cert: Config.tls_crt,
key: Config.tls_key
};
if (Config.tls_crt.indexOf("---") == -1) {
options = {
cert: Buffer.from(Config.tls_crt, 'base64').toString('ascii'),
key: Buffer.from(Config.tls_key, 'base64').toString('ascii')
};
}
var ca: string = Config.tls_ca;
if (ca !== "") {
if (ca.indexOf("---") === -1) {
ca = Buffer.from(ca, 'base64').toString('ascii');
}
if (ca.indexOf("---") > -1) {
options.ca = ca;
}
// options.cert += "\n" + ca;
}
if (Config.tls_passphrase !== "") {
options.passphrase = Config.tls_passphrase;
}
server = https.createServer(options, this.app);
var redirapp = express();
var _http = http.createServer(redirapp);
redirapp.get('*', function (req, res) {
// res.redirect('https://' + req.headers.host + req.url);
res.status(200).json({ status: "ok" });
})
_http.listen(80);
} else {
server = http.createServer(this.app);
}
server.on("error", (error) => {
this._logger.error(error);
console.error(error);
process.exit(404);
});
this.settings = new nodered_settings();
this.settings.userDir = path.join(__dirname, "./nodered");
this.settings.nodesDir = path.join(__dirname, "./nodered");
// this.settings.adminAuth = new googleauth.noderedcontribauthgoogle(Config.baseurl(), Config.consumer_key, Config.consumer_secret,
// (profile:string | any, done:any)=> {
// profile.permissions = "*";
// done(profile);
// });
this.settings.adminAuth = await samlauth.noderedcontribauthsaml.configure(Config.baseurl(), Config.saml_federation_metadata, Config.saml_issuer,
(profile: string | any, done: any) => {
var roles: string[] = profile["http://schemas.xmlsoap.org/claims/Group"];
if (roles !== undefined) {
if (Config.noderedusers !== "") {
if (roles.indexOf(Config.noderedusers) !== -1 || roles.indexOf(Config.noderedusers) !== -1) { profile.permissions = "read"; }
}
if (Config.noderedadmins !== "") {
if (roles.indexOf(Config.noderedadmins) !== -1 || roles.indexOf(Config.noderedadmins) !== -1) { profile.permissions = "*"; }
}
}
// profile.permissions = "*";
done(profile);
}, "");
// this.settings.adminAuth = await noderedcontribauthsaml.configure(this._logger, Config.baseurl());clear
// settings.adminAuth = new noderedcontribauthopenid(this._logger, Config.baseurl());
this.settings.httpNodeMiddleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
noderedcontribmiddlewareauth.process(socket, req, res, next);
};
this.settings.storageModule = new noderedcontribopenflowstorage(logger, socket);
this.settings.ui.path = "ui";
// this.settings.ui.middleware = new dashboardAuth();
this.settings.ui.middleware = (req: express.Request, res: express.Response, next: express.NextFunction) => {
noderedcontribmiddlewareauth.process(socket, req, res, next);
// if (req.isAuthenticated()) {
// next();
// } else {
// passport.authenticate("uisaml", {
// successRedirect: '/ui/',
// failureRedirect: '/uisaml/',
// failureFlash: false
// })(req, res, next);
// }
};
this.app.use(cookieSession({
name: 'session',
keys: ['key1', 'key2']
}))
// initialise the runtime with a server and settings
await (RED as any).init(server, this.settings);
// serve the editor UI from /red
this.app.use(this.settings.httpAdminRoot, RED.httpAdmin);
// serve the http nodes UI from /api
this.app.use(this.settings.httpNodeRoot, RED.httpNode);
server.listen(Config.port);
} else {
await RED.stop();
// initialise the runtime with a server and settings
await (RED as any).init(server, this.settings);
// serve the editor UI from /red
this.app.use(this.settings.httpAdminRoot, RED.httpAdmin);
// serve the http nodes UI from /api
this.app.use(this.settings.httpNodeRoot, RED.httpNode);
}
var hasErrors: boolean = true; var errorCounter: number = 0;
var err: any;
while (hasErrors) {
try {
RED.start();
hasErrors = false;
} catch (error) {
err = error;
errorCounter++;
hasErrors = true;
console.error(error);
}
if (errorCounter == 10) {
throw err;
} else if (hasErrors) {
var wait = ms => new Promise((r, j) => setTimeout(r, ms));
await wait(2000);
}
}
return server;
} catch (error) {
console.error(JSON.stringify(options));
this._logger.error(error);
console.error(error);
process.exit(404);
}
return null;
}
}