-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathindex.ts
269 lines (247 loc) · 7.78 KB
/
index.ts
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
/* eslint-disable react-hooks/rules-of-hooks */
import {OurError} from '@shared/interface/IError';
import IOldWorkspace from '@shared/interface/IOldWorkspace';
import csurf from 'csurf';
import express, {CookieOptions, Request, Response} from 'express';
import session, {SessionOptions} from 'express-session';
import helmet from 'helmet';
import http from 'http';
import {
FORBIDDEN,
INTERNAL_SERVER_ERROR,
NOT_FOUND,
UNAUTHORIZED
} from 'http-status-codes';
import _ from 'lodash';
import 'module-alias/register';
// @ts-ignore
import RightsManagement from 'rights-management';
// @ts-ignore
import Signin from 'signin';
// @ts-ignore
import StartupDiagnostics from 'startup-diagnostics';
import DB from './node-backend/db';
import {buildDBConfig, buildDBUrl} from './node-backend/dbUtil';
import getRequiredRights from './node-backend/getRequiredRights';
import InProgressWorkspaceRepository from './node-backend/inProgressRepository';
import InProgressRouter from './node-backend/inProgressRouter';
import logger from './node-backend/logger';
import OrderingRouter from './node-backend/orderingRouter';
import PataviRouter from './node-backend/pataviRouter';
import {premades} from './node-backend/premades';
import ScenarioRouter from './node-backend/scenarioRouter';
import SubproblemRouter from './node-backend/subproblemRouter';
import WorkspaceRepository from './node-backend/workspaceRepository';
import WorkspaceRouter from './node-backend/workspaceRouter';
import WorkspaceSettingsRouter from './node-backend/workspaceSettingsRouter';
const db = DB(buildDBConfig());
logger.info(buildDBUrl());
const appEnvironmentSettings = {
googleKey: process.env.MCDAWEB_GOOGLE_KEY,
googleSecret: process.env.MCDAWEB_GOOGLE_SECRET,
host: process.env.MCDA_HOST
};
const signin = Signin(db, appEnvironmentSettings);
const inProgressWorkspaceRepository = InProgressWorkspaceRepository(db);
const workspaceRepository = WorkspaceRepository(db);
const workspaceRouter = WorkspaceRouter(db);
const inProgressRouter = InProgressRouter(db);
const orderingRouter = OrderingRouter(db);
const subproblemRouter = SubproblemRouter(db);
const scenarioRouter = ScenarioRouter(db);
const workspaceSettingsRouter = WorkspaceSettingsRouter(db);
const pataviRouter = PataviRouter(db);
const startupDiagnostics = StartupDiagnostics(db, logger, 'MCDA');
const rightsManagement = RightsManagement();
let server: http.Server;
let authenticationMethod = process.env.MCDAWEB_AUTHENTICATION_METHOD;
const app = express();
app.use(helmet());
app.set('trust proxy', 1);
app.use(
express.json({
limit: '5mb'
})
);
server = http.createServer(app);
function runDiagnostics(numberOftries: number) {
startupDiagnostics.runStartupDiagnostics((errorBody: OurError): void => {
if (numberOftries <= 0) {
process.exit(1);
} else if (errorBody) {
setTimeout(_.partial(runDiagnostics, numberOftries - 1), 10000);
} else {
initApp();
}
});
}
runDiagnostics(6);
function initApp(): void {
rightsManagement.setRequiredRights(
getRequiredRights(workspaceOwnerRightsNeeded, inProgressOwnerRightsNeeded)
);
const cookieSettings: CookieOptions = {
maxAge: 60 * 60 * 1000, // 1 hour,
secure: authenticationMethod === 'SSL',
sameSite: authenticationMethod === 'SSL' ? 'strict' : 'lax'
};
const sessionOptions: SessionOptions = {
store: new (require('connect-pg-simple')(session))({
conString: buildDBUrl()
}),
secret: process.env.MCDAWEB_COOKIE_SECRET,
resave: false,
proxy: true,
rolling: true,
saveUninitialized: true,
cookie: cookieSettings
};
app.use(session(sessionOptions));
switch (authenticationMethod) {
case 'SSL':
useSSLLogin();
break;
case 'LOCAL':
signin.useLocalLogin(app);
break;
default:
authenticationMethod = 'GOOGLE';
signin.useGoogleLogin(app);
}
logger.info('Authentication method: ' + authenticationMethod);
app.get('/logout', (request: Request, response: Response): void => {
request.logout();
request.session.destroy((error) => {
response.redirect('/');
});
});
app.use(csurf());
app.use((request: Request, response: Response, next: any): void => {
response.cookie('XSRF-TOKEN', request.csrfToken(), cookieSettings);
if (request.user) {
response.cookie(
'LOGGED-IN-USER',
JSON.stringify(_.omit(request.user, 'email', 'password')),
cookieSettings
);
}
next();
});
app.use(express.static(__dirname + '/dist'));
app.use(express.static('public'));
app.use('/img', express.static('tutorials/fig'));
app.use('/css/fonts', express.static(__dirname + '/dist/fonts'));
app.use('/api', rightsManagement.expressMiddleware);
app.use('/api/v2/inProgress', inProgressRouter);
app.use('/api/v2/workspaces', workspaceRouter);
app.use('/api/v2/workspaces', orderingRouter);
app.use('/api/v2/workspaces', subproblemRouter);
app.use('/api/v2/workspaces', scenarioRouter);
app.use('/api/v2/workspaces', workspaceSettingsRouter);
app.use('/api/v2/premades', (request: Request, response: Response) => {
response.json(premades);
});
app.use('/api/v2/patavi', pataviRouter);
app.use(errorHandler);
// Default route (ALWAYS Keep this as the last route)
app.get('*', (request: any, response: Response): void => {
if (request.user || request.session.user) {
response.sendFile(__dirname + '/dist/app.html');
} else {
response.sendFile(__dirname + '/dist/signin.html');
}
});
startListening((port: string): void => {
logger.info('Listening on http://localhost:' + port);
});
}
function errorHandler(
error: OurError,
_request: Request,
response: Response,
next: any
): void {
logger.error(JSON.stringify(error.message, null, 2));
if (error?.type === signin.SIGNIN_ERROR) {
response.status(UNAUTHORIZED).send('login failed');
} else if (error) {
const errorMessage = error.err ? error.err.message : error.message;
response
.status(error.status || error.statusCode || INTERNAL_SERVER_ERROR)
.send(errorMessage);
} else {
next();
}
}
function startListening(listenFunction: (port: string) => void): void {
const port = getPort();
server.listen(port, _.partial(listenFunction, port));
}
function getPort(): string {
if (process.argv[2] === 'port' && process.argv[3]) {
return process.argv[3];
} else {
return '3002';
}
}
function workspaceOwnerRightsNeeded(
response: Response,
next: any,
workspaceId: string,
userId: number
): void {
workspaceRepository.get(
workspaceId,
_.partial(rightsCallback, response, next, userId)
);
}
function inProgressOwnerRightsNeeded(
response: Response,
next: any,
workspaceId: string,
userId: number
): void {
inProgressWorkspaceRepository.get(
workspaceId,
_.partial(rightsCallback, response, next, userId)
);
}
function rightsCallback(
response: Response,
next: any,
userId: number,
error: OurError,
result: any
): void {
if (error) {
next(error);
} else {
const workspace: IOldWorkspace = result;
if (!workspace) {
response.status(NOT_FOUND).send('Workspace not found');
} else if (workspace.owner !== userId) {
response.status(FORBIDDEN).send('Insufficient user rights');
} else {
next();
}
}
}
function useSSLLogin(): void {
app.get('/signin', (request: any, response: Response) => {
const clientString = request.header('X-SSL-CLIENT-DN');
const emailRegex = /emailAddress=([^,]*)/;
const email = clientString.match(emailRegex)[1];
if (email) {
signin.findUserByEmail(email, (error: OurError, result: any) => {
if (error) {
logger.error(error);
} else {
request.session.user = result;
request.session.save(() => {
response.redirect('/');
});
}
});
}
});
}