-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
369 lines (329 loc) · 13.2 KB
/
server.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
require('newrelic');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var cors = require('cors');
var LocalStrategy = require('passport-local').Strategy;
var jwt = require('jwt-simple');
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var sa = require('superagent');
var reportService = require('./services/reportService');
var providerService = require('./services/providerService');
var locationService = require('./services/locationService');
var userService = require('./services/userService');
var User = require('./models/User');
var json2csv = require('json2csv');
var contracts = require('./contracts');
var R = require('ramda');
var PythonShell = require('python-shell');
var moment = require('moment');
var db = require('./models/db');
app.use(bodyParser.json());
app.use(cors());
var tokenSecret = 'verySecret';
var ipToAsMap = {};
passport.use(new LocalStrategy(
function(username, password, done) {
User.where('username', username).fetch().then((user) => {
if (!user) {
return done(null, false, { reason: 'Incorrect username.' });
}
if (user.get('password') !== userService.hashPassword(password, user.get('salt'))) {
return done(null, false, { reason: 'Incorrect password.' });
}
return done(null, user.toJSON());
});
}
));
passport.use(new JwtStrategy({ secretOrKey: tokenSecret, jwtFromRequest: ExtractJwt.fromAuthHeader() },
function(jwt_payload, done) {
if (!jwt_payload.expires || moment(jwt_payload.expires) < moment()) {
done(null, false);
return;
}
User.where('username', jwt_payload.userId).fetch().then((user) => {
if (user) {
done(null, user.toJSON());
} else {
done(null, false);
}
});
}
));
passport.use(new BasicStrategy(
function(userid, password, done) {
User.where('username', userid).fetch().then((user) => {
if (!user) { return done(null, false); }
if (userService.hashPassword(password, user.get('salt')) !== user.get('password')) { return done(null, false); }
return done(null, user.toJSON());
});
}
));
app.get('/api', function(req, res) {
res.send('')
})
app.post('/api/register', function(req, res) {
const user = req.body;
console.log(user);
if (!user.captcharesponse || !user.username || !user.password1 || !user.password2 || user.password1 !== user.password2) {
res.status(400).json({ reason: 'Incomplete parameters' });
return;
}
sa.post('https://www.google.com/recaptcha/api/siteverify')
.send({
secret: process.env.RECAPTCHA_SECRET_KEY,
response: user.captcharesponse,
remoteip: req.connection.remoteAddress
})
.end(function(err, response) {
if (err) {
console.log(err);
res.status(403).json({ reason: 'Error while processing Captcha' });
}
userService.createUser(user.username, user.password1).then((user) => {
res.send(contracts.userContract(user));
}, (error) => {
res.status(403).json({ reason: 'Error while creating user' });
})
})
})
app.post('/api/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
if (err) { return next(err) }
if (!user) {
return res.status(401).json({ reason: 'User/Password incorrect' });
}
var expireDate = moment().add(1, "days");
var token = jwt.encode({ userId: user.username, expires: expireDate }, tokenSecret);
res.status(200).json({ token: token, username: user.username, id: user.id, role: user.role });
})(req, res, next);
})
app.post('/api/recover', function(req, res) {
var email = req.body.email
if (!email) { res.status(400).json({ reason: 'Incomplete parameters' }) };
userService.sendUserRecoveryEmail(email).then((answer) => res.status(200).json({ reason: 'Recovery code sent successfully' }));
})
app.post('/api/recover/code', function(req, res) {
var email = req.body.email;
var code = req.body.code;
var password = req.body.password
if (!email || !code || !password) { res.status(400).json({ reason: 'Incomplete parameters' }) };
userService.updatePassword(email, code, password).then((answer) => res.status(200).json({ reason: 'Password updated successfully' }));
})
app.all('/api/user/*', passport.authenticate(['jwt', 'basic'], { session: false }), function(req, res, next) {
next();
})
app.all('/api/admin/*', passport.authenticate(['jwt', 'basic'], { session: false }), function(req, res, next) {
const user = req.user;
if (user.role !== 'admin') {
res.status(401).json({ reason: 'You are not authorized to perform that action' })
} else {
next();
}
})
app.get('/api/user/current', function(req, res) {
var user = req.user;
res.send({
username: user.username,
role: user.role,
id: user.id,
enabled: user.enabled
});
})
app.get('/api/user/current/installation', function(req, res) {
locationService.getInstallationByUserId(req.user.id).then((locations) => {
res.send(R.map(contracts.installationContract, locations));
});
})
app.get('/api/user/:id', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
userService.getUserById(req.params.id).then((user) => {
res.send(contracts.userContract(user));
});;
})
app.put('/api/user/:id', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
var body = req.body;
var userId = req.params.id;
if (body.role && req.user.role !== 'admin') {
res.status(403).json({ reason: 'The user cannot perform that operation' });
return;
}
userService.updateUser(body, userId, req.user.role === 'admin').then((user) => {
if (user) {
res.send(contracts.userContract(user));
} else {
res.code(403).json({ reason: 'passwords do not match' });
};
});
})
app.post('/api/user/:id/installation', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const user = req.user;
const location = req.body;
locationService.createInstallation(location, user).then((location) => {
res.send(contracts.installationContract(location));
});;
})
app.get('/api/user/:id/installation', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const userId = req.params.id;
locationService.getInstallations(userId).then((locations) => { res.send(locations.map((location) => contracts.installationContract(location))); });;
})
app.get('/api/user/:id/installation/:installationId', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const userId = req.params.id;
const installationId = req.params.installationId;
locationService.getInstallation(installationId, userId).then((installation) => {
if (installation) {
res.send(contracts.installationContract(installation));
} else {
res.status(404).send("Not Found");
}
});
})
app.put('/api/user/:id/installation/:installationId', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const name = req.body.name;
const userId = req.params.id;
const installationId = req.params.installationId;
locationService.updateInstallation(installationId, userId, name).then(installation => res.send(contracts.installationContract(installation)));
})
app.delete('/api/user/:id/installation/:installationId', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const userId = req.params.id;
const installationId = req.params.installationId;
locationService.deleteInstallation(installationId, userId).then(installation => res.send(contracts.installationContract(installation)));;
})
app.get('/api/user/:id/provider', function(req, res) {
providerService.getProviders().then((providers) => res.send(providers.map(provider => contracts.providerContract(provider))));;
})
app.get('/api/user/:id/provider/:providerId', function(req, res) {
const {
providerId
} = req.params;
providerService.getProvider(providerId).then((providers) => res.send(providers.map(provider => contracts.providerContract(provider))));;
})
app.get('/api/user/:id/reports', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const {
startDate,
endDate,
providerId,
installationId,
} = req.query;
const userId = req.params.id;
reportService.getReports(userId, installationId, providerId, startDate, endDate).then((reports) => {
res.send(reports.map((report) => contracts.measureContract(report)));
});
})
app.post('/api/user/:id/installation/:installationId/reports', function(req, res) {
if (req.user.id !== parseInt(req.params.id) && req.user.role !== 'admin') {
res.status(401).json({ reason: 'The user cannot perform that operation' });
return;
}
const installationId = req.params.installationId;
const userId = req.params.id;
const report = req.body;
if (!ipToAsMap[report.ip] || ipToAsMap[report.ip].date < moment().subtract(1, "days")) {
var options = {
scriptPath: 'ipToAs',
args: [report.ip]
};
PythonShell.run('info.py', options, function(err, result) {
if (err) {
res.status(500).send(`Could not calculate ipToAs: ${err}`);
console.log(err);
return;
}
const as = result[0].split(',')[0];
ipToAsMap[report.ip] = {};
ipToAsMap[report.ip].as = as;
ipToAsMap[report.ip].date = moment();
reportService.postReport(report, as, installationId, userId).then((measure) => res.send(contracts.measureContract(measure)));
});
} else {
reportService.postReport(report, ipToAsMap[report.ip].as, installationId, userId).then((measure) => res.send(contracts.measureContract(measure)));
}
})
app.get('/api/admin/users', function(req, res) {
const user = req.user;
if (user.role === 'admin') {
userService.getAllUsers().then((users) => {
res.send(R.map(contracts.userContract, users));
});
} else {
res.status(401).json({ reason: "You are not authorized to perform that action" });
}
})
app.get('/api/admin/reports', function(req, res) {
const {
startDate,
endDate,
providerId,
} = req.query;
reportService.getAdminReports(startDate, endDate, providerId).then((reports) => {
res.send(reports.map((report) => contracts.measureContract(report)));
});
});
app.get('/api/admin/reports.csv', function(req, res) {
const {
startDate,
endDate,
providerId,
} = req.query;
reportService.getAdminReports(startDate, endDate, providerId).then((reports) => {
json2csv({ data: reports.toJSON(), fields: ['timestamp', 'upUsage', 'downUsage', 'upQuality', 'downQuality'] }, function(err, csv) {
res.setHeader('Content-disposition', 'attachment; filename=data.csv');
res.set('Content-Type', 'text/csv');
res.status(200).send(csv);
});
});
});
if (process.env.NODE_ENV != 'test') {
db.migrate().then(() => {
const admin_user = process.env.TIX_API_USER;
const admin_pass = process.env.TIX_API_PASSWORD;
userService.createAdmin(admin_user, admin_pass).then((user) => {
console.log(`Created admin user: ${process.env.TIX_API_USER}`)
}, (error) => {
console.log(`Failed creating admin user: ${error}`)
});
app.listen(3001, function() {
console.log('TiX api app listening on port 3001!')
});
}, (error) => {
console.log(`Failed migrations: ${error}`)
});
} else {
app.listen(3001, function() {
console.log('TiX api app listening on port 3001!')
});
}