-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
294 lines (243 loc) · 7.15 KB
/
index.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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Load external modules
const express = require('express');
const path = require('path');
var bodyParser = require('body-parser');
var http = require('http');
var session = require('express-session');
var rest = require('./rest-interface.js');
var util = require('./util.js');
var passport = require('passport');
var mongoose = require('mongoose');
var allConfigs = require('./server-configs.js');
// Routing modules
var paperRoutes = require('./routes/paper.js');
var authRoutes = require('./routes/auth.js')(passport);
var usersRoutes = require('./routes/users.js');
// Local and REST server config
var serverConfig = {};
if (process.argv.length == 3) {
var configName = process.argv[2];
var config = allConfigs[configName];
if (config) {
serverConfig = config;
} else {
console.log("[ERROR] No server configurations detected, exiting");
process.exit();
}
}
util.serverConfig = serverConfig;
var nsSubdomain = "fabric";
var nsDomain = "hyperledger";
var nsClient = "cp";
var namespace = nsSubdomain + '.' + nsDomain + '.' + nsClient;
util.namespace = namespace;
const composerServerConfig = {
"protocol": "http://",
"host": "localhost",
"port": 3000,
"loginPath": "/auth/github",
"namespace": namespace
}
var loginURL = composerServerConfig.protocol + composerServerConfig.host + ':' + composerServerConfig.port + composerServerConfig.loginPath;
rest.setServerConfig(composerServerConfig);
// Mongoose config
mongoose.connect(serverConfig.dbURL, { useMongoClient: true });
var db = mongoose.connection;
db.on('error', (err) => {
console.log("[ERROR]", err);
});
db.once('open', () => {
console.log("[INFO]", "Connected to MongoDB");
});
// Get the express server
const app = express();
// Express settings
app.set('view engine', 'pug');
// Express middleware
app.use('/static', express.static(path.join(__dirname, serverConfig.staticDir)));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(session({
secret: 'kitty',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
// Custom middleware
// Build the viewData object if it doesn't exist
app.use((req, res, next) => {
if (!res.viewData) {
res.viewData = {};
}
next();
});
// Retrieve company info for the UI and add it to the viewData
app.use((req, res, next) => {
if (!req.user || req.originalUrl == '/logout') {
res.viewData.companyInfo = { name: serverConfig.company }
return next();
}
rest.getCompany(util.serverConfig.company, util.serverConfig.token, (getCompanyRes, getCompanyErr) => {
if (getCompanyErr) {
getCompanyErr.handler.redirect = '/login';
return next(getCompanyErr);
}
res.viewData.companyInfo = getCompanyRes;
next();
});
});
// Place the user in viewData if logged in
app.use((req, res, next) => {
if (req.user) {
res.viewData.currentUser = req.user;
}
next();
});
// Load routing modules
app.use('/paper', paperRoutes);
app.use('/auth', authRoutes);
app.use('/users', usersRoutes);
// Root routes
app.get('/', (req, res, next) => {
if (req.user) {
return res.redirect('/paper');
}
util.clearGuards(req);
res.viewData.flash = util.getFlash(req);
res.render('login', res.viewData);
});
app.get('/login', (req, res) => {
if (req.user) {
return res.redirect('/paper');
}
util.clearGuards(req);
res.viewData.flash = util.getFlash(req);
res.render('login', res.viewData);
});
app.get('/logout', (req, res) => {
req.logout();
util.flashSuccess(req, 'You were logged out');
res.redirect('/');
});
// Guard against redirection loops by logging out
app.use((err, req, res, next) => {
if (err.handler) {
if (!req.session.redirectGuards) {
req.session.redirectGuards = {};
}
var guardValue = req.session.redirectGuards[err.handler.redirect];
if (!guardValue) {
req.session.redirectGuards[err.handler.redirect] = 1;
} else {
if (guardValue >= 1) {
req.logout();
util.flashSuccess(req, 'You were logged out');
util.clearGuards(req);
res.viewData.flash = util.getFlash(req);
return res.render('login', res.viewData);
} else {
req.session.redirectGuards[err.handler.redirect] += 1;
}
}
}
return next(err);
});
// Log errors if debug is enabled
app.use((err, req, res, next) => {
if (serverConfig.debug) {
console.log("[ERROR]");
console.log(err);
}
return next(err);
});
// Set default message and redirect if none given for each type of error
app.use((err, req, res, next) => {
var msg = 'There was an error';
var redirect = '/logout';
if (err.handler && err.handler.type) {
switch(err.handler.type) {
case util.ERROR_TYPES.COMPOSER_REST_HTTP_ERROR:
msg = 'An HTTP error occurred during a call to the REST server, check server logs';
redirect = '/paper';
break;
case util.ERROR_TYPES.COMPOSER_REST_ERROR:
msg = 'A REST server error occurred';
redirect = '/paper';
if (err.handler.subtype) {
if (err.handler.subtype == util.COMPOSER_REST_ERROR_TYPES.AUTH) {
msg = 'Not authenticated to the REST server';
}
else if (err.handler.subtype == util.COMPOSER_REST_ERROR_TYPES.ENROLL) {
msg = 'No default identity enrolled or selected on the REST server';
}
}
break;
case util.ERROR_TYPES.VALIDATION_ERROR:
msg = 'A field was inputted incorrectly';
redirect = '/paper';
break;
case util.ERROR_TYPES.AUTHENTICATION_ERROR:
msg = 'You must be authenticated to perform this action';
redirect = '/login';
break;
case util.ERROR_TYPES.USER_ALREADY_EXISTS_ERROR:
msg = 'This user already exists';
redirect = '/auth/local/register';
break;
case util.ERROR_TYPES.MONGOOSE_ERROR:
msg = 'There was a database error, could not perform action';
redirect = '/paper';
break;
case util.ERROR_TYPES.CRYPTO_ERROR:
msg = 'There was an error while performing cryptographic functions';
redirect = '/paper';
break;
case util.ERROR_TYPES.NOT_ALLOWED_ERROR:
msg = 'You do not have sufficient permissions to perform this action';
redirect = '/paper';
break;
case util.ERROR_TYPES.INVALID_ROLE_ERROR:
msg = 'Invalid role type selected';
redirect = '/auth/local/register';
break;
}
err.handler.msg = err.handler.msg || msg;
err.handler.redirect = err.handler.redirect || redirect;
}
return next(err);
});
// Set the error message flash and redirect
app.use((err, req, res, next) => {
if (err.handler) {
util.flashError(req, err.handler.msg);
return res.redirect(err.handler.redirect);
}
return next(err);
});
// Handle unhandled errors
app.use((err, req, res, next) => {
// Let the default Pug error handler send error to the browser
if (err.code) {
if (err.code.substring(0, 3) == 'PUG') {
return next(err);
}
}
// If debug is enabled, send the full error to the browser
if (serverConfig.debug) {
return res.send(err.toString());
} else {
return res.send("[ERROR] A fatal error occurred");
}
});
// Start listening
app.listen(serverConfig.port, () => {
console.log("[INFO] Started listening on", serverConfig.port);
});
// On exit, close MongoDB connection
process.on('SIGINT', cleanup);
function cleanup() {
console.log("[INFO] Closing MongoDB connection");
mongoose.disconnect();
process.exit();
}