-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.js
More file actions
executable file
·473 lines (439 loc) · 17.3 KB
/
api.js
File metadata and controls
executable file
·473 lines (439 loc) · 17.3 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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
/**
* @author
* @copyright
*/
var g = require('./global.js'),
push = require('./push.js'),
url = require('url'),
bcrypt = require('bcrypt');
var self;
var that;
module.exports = {
/**
* API response object.
* @param code (number) 0 - success, otherwise error
* msg (string) Empty if success, otherwise an error message
* ret (?) The return value (can be a primitive or an object)
*/
_res: function (code, msg, ret) {
return JSON.stringify({
'code': code, 'msg': msg, 'ret': ret,
});
},
_success: function (ret) {
return that._res(0, '', ret);
},
_error: function (code, msg) {
return that._res(code, msg, null);
},
/* Errors */
_error_codes: {
'generic' : [101, 'Problem invoking API function'],
'not_found': [102, 'Not found'],
'malformed_request': [103, 'Malformed request'],
'bad_auth' : [104, 'Bad authentication credentials'],
},
error: function (name) {
return that._error(that._error_codes[name][0], that._error_codes[name][1]);
},
_requestFilters: {
'/api/push': [],
},
is_valid: function (req) {
var urlParts = url.parse(req.url, true);
var filters = that._requestFilters[urlParts.pathname];
if (g.isset(filters)) {
for (var i = 0; i < filters.length; i++) {
//if (that[filters[i]](req)) {
// return false;
//}
}
}
return true;
},
WS_STAT: 'stat',
notify_status: function (clientId, status) {
var data = {
clientId: clientId, status: status,
};
g.io.sockets.in(g.roomTrackers(clientId)).emit(self.WS_STAT, JSON.stringify(data));
},
gen_token: function (clientId) {
//var str = clientId + new Date().getTime() + Math.floor(Math.random() * 8);
//return bcrypt.hashSync(str, 1);
var rpart = "";
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i = 0; i < 8; i++) {
rpart += chars.charAt(Math.floor(Math.random() * chars.length));
}
// For now, does not expire
return clientId + "-0-" + rpart;
},
// TODO - Implement time-constant token validation
verify_token: function (clientId, token) {
if (!g.isset(g['tokens'][clientId])) {
g.debug('verify_token - not set for {0}'.format(clientId));
// Check if the token is stored in redis / mysql
return false;
}
var persisted = g['tokens'][clientId];
console.log('verify_token - comparing provided ' + token + ' with persisted ' + persisted);
// XXX - Need to check expiryTs
return persisted == token;
},
'/api/authenticate': function (params, fn) {
var username = params['username'],
password = params['password'],
token = params['token'],
type = params['type'], // customer, driver, admin, or system
table = g.mysql[type];
if (!g.isset(username) || (!g.isset(password) && !g.isset(token)) || !g.isset(type)) {
fn(self._error(1, 'Missing username, password, or login type'));
return;
}
if (!g.isset(table)) {
g.error('Error - unrecognized type {0}'.format(type));
fn(self._error(1, 'Login type ' + type + ' not recognized'));
return;
}
g.debug('Fetching authentication credentials');
if (token) {
try {
table.getAuth(username, function (rows) {
if (rows == null)
{
fn(self._error(1, 'Database error during authentication (1)'));
}
else if (rows[0]['api_token'] == token)
{
var clientId = type.charAt(0) + "-" + rows[0]['pk']; // c-123
var dummy = clientId + '-0-' + rows[0]['api_token']; // Node-format
g.tokens[clientId] = dummy;
fn(that._success({ token: dummy }));
}
else
{
g.debug(rows);
g.debug(rows[0]['api_token']);
g.debug(token);
fn(self.error('bad_auth'));
}
});
} catch (err) {
fn(self._error(1, 'Database error during authentication (2)'));
}
return;
}
table.getAuth(username, function (res) {
if (res == null) {
fn(self._error(1, 'Database error during authentication'));
} else if (res.length > 0 && !g.empty(res[0]['pk']) && !g.empty(res[0]['password'])) {
var pk = res[0]['pk'];
var clientId = '{0}-{1}'.format(type.substring(0, 1), pk); // c-500
var hash = res[0]['password'];
// Laravel generates bcrypt hashes with a new "2y" prefix (to address a bug in PHP) that is
// not compatible with other Java/JavaScript libraries
hash = hash.replace(/^\$2y/, '$2a');
// Async compare using bcrypt
bcrypt.compare(password, hash, function (err, res) {
if (err) {
// error with bcrypt
var msg = 'Error with bcrypt - ' + err;
fn(self._error(1, msg));
} else if (res) {
// Good - check if an API token has already been generated for another user instance
if (g.tokens[clientId] != null) {
fn(self._success({ token: g.tokens[clientId] }));
return;
}
// If none exist, generate a new one
var token = self.gen_token(clientId); // d-890-0yH5ob94
var ret = { token: token };
// Write token to database
table.updateToken(pk, token, function (res) {
if (res == null) {
fn(that._error(1, 'Error writing token to database'));
} else {
g.debug('Assigned {0} access token {1}'.format(clientId, token));
g.tokens[clientId] = token;
fn(that._success(ret));
}
});
} else {
fn(that.error('bad_auth'));
}
});
} else {
// This makes the server vulnerable to scraping attacks (testing only)
fn(that._error(1, 'database query came back empty; user ' + username + ' not found'));
}
});
},
'/api/greet': function (params, fn) {
console.log('connected - ' + Object.keys(g.io.sockets.connected));
var clientId = params['uid'];
fn(that._success('Hello, ' + clientId + '!'));
},
'/api/test': function (params, fn) {
fn(self._success("ok"));
},
'/api/connected': function (params, fn) {
var ret = g.isconnected(params['clientId']);
fn(self._success(ret));
},
/** Push notifications **/
_cacheKeyGroup: function (name) {
return 'group_' + name;
},
// XXX: Guard against cross-user modification
'/api/modgrp': function (params, fn) {
var cmd = params['cmd'], uid = params['uid'], group = params['group'];
if (!g.isset(cmd) || !g.isset(uid) || !g.isset(group)) {
fn(self._error(1, 'Error - cmd, uid, or group parameter not found'));
} else {
switch (cmd) {
case 'a':
g['redis'].SADD(self._cacheKeyGroup(group), uid, function (err, ret) {
if (err != null) {
fn(self._error(1, err));
} else {
fn(self._success(null));
}
});
case 'd':
case 'D':
// Delete a group
break;
default:
fn(self._error(1, 'Error - command ' + cmd + ' not supported'));
}
}
},
// Ready for push data via WebSocket
'/api/ready': function (params, fn) {
var uid = params['uid'],
sid = params['sid'];
if (!g.isset(sid)) {
throw 'Error - parameter sid (socket identifier) not found; make sure /api/ready is called via WebSocket';
}
var soc = g.io.sockets.connected[sid];
if (!g.isset(soc)) {
fn(self._error(1, "Something is very wrong - socket object doesn't exist"));
} else {
soc.ready = true;
soc.join(String(uid));
g.debug('{0} joined room(s) {1}'.format(soc.name, uid));
// If client is admin, automatically add to "atlas" group
if (uid.split('-')[0] == 'a') {
g.debug('Trying to automatically add {0} to "atlas" group'.format(soc.name));
// TODO - Groups shouldn't be lazily loaded
//soc.join('atlas');
// persist client to group on redis so push notifications are properly queued
g.redis.SADD(self._cacheKeyGroup('atlas'), uid, function (err, ret) {
if (err != null) {
g.error('Error - Problem adding client {0} to group "atlas"'.format(uid));
} else {
g.debug('Added {0} to group "atlas"'.format(uid));
}
});
}
g['redis'].SMEMBERS(self._cacheKeyTrackList(uid), function (err, ret) {
if (err) {
fn(self._error(1, 'Error getting subscriptions for ' + self._cacheKeyTrackList(uid) + ' - ' + err));
} else if (g.isset(soc)) {
var rooms = [];
for (var i = 0; i < ret.length; i++) {
var room = g.roomTrackers(ret[i]);
rooms.push(room);
soc.join(room);
}
g.debug('{0} joined room(s) {1}'.format(soc.name, rooms.join(", ")));
fn(self._success('ok'));
}
});
push.flush(uid);
}
},
'/api/push': function (params, fn) {
var rid = g.getOrElse(params['rid'], null);
from = params.from,
to = params.to,
subject = params.subject,
body = params.body;
if (!g.isset(to) || !g.isset(subject) || !g.isset(body)) {
if (g.isset(fn)) fn(self._error(1, 'Missing to, subject, or body parameter(s)'));
return;
}
var timestamp = g.getOrElse(params['timestamp'], new Date().getTime());
var p = {
rid: rid, from: from, to: to, subject: subject, body: JSON.parse(body), timestamp: timestamp,
};
console.log(typeof to + "(" + to + ")");
var recipient = JSON.parse(to);
if (recipient instanceof Array) {
// Enqueue push notification then schedule a pop
for (var i = 0; i < recipient.length; i++) {
p.to = recipient[i];
push.send(String(recipient[i]), JSON.stringify(p));
}
if (g.isset(fn)) fn(self._success('ok'));
} else if ('*' === recipient) {
if (g.isset(fn)) fn(self._error(1, 'Error - global pushes currently not supported'));
} else {
g['redis'].SMEMBERS(self._cacheKeyGroup(recipient), function (err, ret) {
if (err != null) {
g.error('Error getting members for ' + that._cacheKeyGroup(recipient) + ' - ' + err);
} else {
for (var i = 0; i < ret.length; i++) {
push.send(String(ret[i]), JSON.stringify(p));
}
if (g.isset(fn)) fn(that._success('ok'));
}
}); // g['redis'].SMEMBERS
}
},
/* Tracking */
WS_LOC: 'loc',
_cacheKeyLatLng: function (uid) {
return uid + '_latlng';
},
_cacheKeySubscribers: function (uid) {
return uid + '_subscribers';
},
_cacheKeyTrackList: function (uid) {
// {0}_ does't work here!
return uid + '_trackList';
},
/**
* Get client location via get request.
* e.g.: https://node.bentonow.com:8443/api/gloc?token=c-1-0-randombits&clientId=d-8
*
* Get the client location via the existing socket
* e.g.: sock.emit('get', '/api/gloc?clientId=d-8', callbackFn(res));
* Sockets have no concept of get or post.
*
* clientId=d-8
* See db.js for other prefixes
*
* @param {type} params
* @param {type} fn
* @returns {undefined}
*/
'/api/gloc': function (params, fn) {
var uid = params['uid'],
clientId = params['clientId'];
if (g.empty(clientId)) {
fn(self._error(1, 'Error - Missing clientId parameter'));
return;
}
//g.debug("GET " + self._cacheKeyLatLng(clientId));
g['redis'].GET(self._cacheKeyLatLng(clientId), function (err, ret) {
if (err) {
fn(self._error(1, 'Error fetching ' + self._cacheKeyLatLng(clientId) + ' - ' + err));
} else {
var obj = null;
//g.debug("/api/gloc " + ret);
if (!g.empty(ret)) {
obj = JSON.parse(ret);
obj.clientId = clientId;
}
fn(self._success(obj));
}
});
},
/**
* Set location.
*
* @param {type} params
* @param {type} fn
* @returns {undefined}
*/
'/api/uloc': function (params, fn) {
var uid = params['uid'],
lat = params['lat'],
lng = params['lng'],
obj = {
'lat': lat, 'lng': lng,
};
// First persist coordinates to redis
g['redis'].SET(self._cacheKeyLatLng(uid), JSON.stringify(obj), function (err, ret) {
if (err) {
fn(self._error(1, err));
} else {
fn(self._success("ok"));
// Then push loc update to all subscribers
obj.clientId = uid;
g.io.sockets.in(g.roomTrackers(uid)).emit('loc', JSON.stringify(obj));
}
}); // g['redis'].SET
},
/**
*
* https://bentonow.slack.com/archives/engineering/p1458164194000005
* On the client (app), you need to filter for stale data, and then untrack accordingly
*
* @param {type} params
* @param {type} fn
* @returns {undefined}
*/
'/api/track': function (params, fn) {
var uid = params['uid'],
clientId = params['clientId'];
if (!g.isset(uid) || !g.isset(clientId)) {
fn(self._error(1, 'Error - missing paramters uid or clientId'));
return;
}
// TODO - add uid to client's subscribers list also
//console.log('SADD ' + self._cacheKeyTrackList(uid) + ' ' + clientId);
g['redis'].SADD(self._cacheKeyTrackList(uid), clientId, function (err, ret) {
if (err) {
fn(self._error(1, err));
}
else {
g.nio.broadcastTrack(uid, clientId);
var connected = g.isconnected(clientId);
fn(self._success({
'clientId': clientId, 'connected': connected,
}));
/*
// Then if there's any location data available, immediately send it.
// XXX: Do not send stale location data. Maybe only send if client is online?
if (!connected) {
return;
}
*/
}
}); // g['redis'].SADD
},
'/api/untrack': function (params, fn) {
var uid = params['uid'],
clientId = params['clientId'];
if (!g.isset(uid) || !g.isset(clientId)) {
fn(self._error(1, 'Error - missing paramters uid or clientId'));
return;
}
g['redis'].SREM(self._cacheKeyTrackList(uid), clientId, function (err, ret) {
if (err) {
fn(self._error(1, err));
} else {
g.nio.broadcastTrack(uid, clientId, true); // untrack=true
var connected = g.isconnected(clientId);
fn(self._success({
'clientId': clientId, 'connected': connected,
}));
}
}); // g['redis'].SREM
},
'/api/trklst': function (params, fn) {
var uid = params['uid'];
g['redis'].SMEMBERS(self._cacheKeyTrackList(uid), function (err, ret) {
if (err) {
fn(self._error(1, err));
} else {
fn(self._success(ret));
}
}); // g['redis'].SMEMBERS
},
};
that = module.exports;
self = module.exports;