/
mongoclikker.js
457 lines (411 loc) · 15.8 KB
/
mongoclikker.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
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
/**
* Default mongoclikker connection settings
* */
var mongoclikkerConnection = {
host : 'localhost'
, port : '27017'
, user : ''
, pass : ''
, db : 'mongoclikker'
, web : '2002'
, auth : {
user : ''
, pass : ''
}
};
/**
* Set hostname for connection
* @param string host hostname
* @return object mongoclikker
* */
var funcSetHost = function(host) {
mongoclikkerConnection.host = host;
return this;
};
/**
* Set port for connection
* @param integer port port
* @return object mongoclikker
* */
var funcAndPort = function(port) {
mongoclikkerConnection.port = port;
return this;
};
/**
* Set username for connection
* @param string user username
* @return object mongoclikker
* */
var funcWithUser = function(user) {
mongoclikkerConnection.user = user;
return this;
};
/**
* Set password for connection
* @param string password password
* @return object mongoclikker
* */
var funcAndPassword = function(password) {
mongoclikkerConnection.pass = password
return this;
};
/**
* Set database name for connection
* @param string database database name
* @return object mongoclikker
* */
var funcforDatabase = function(database) {
mongoclikkerConnection.db = database;
return this;
};
/**
* Set port for web interface
* @param integer port web interface listens on (Default: 2002)
* @return object mongoclikker
* */
var funcAndListenOn = function(port) {
mongoclikkerConnection.web = port;
funcStartMongoclikker();
};
/**
* Protect mongoclikker with HTTP Authentication.
* @param string user username
* @param string pass password
* @return object mongoclikker
* */
var funcProtectWithUser = function(user, pass) {
if (!pass || pass == '') {
throw new Error("Missing password! Mongoclikker has to be started with user and password to avoid external abuse");
}
mongoclikkerConnection.auth.user = user;
mongoclikkerConnection.auth.pass = pass;
return this;
};
/**
* End mongoclikker interface response
* @param object res response object
* */
function endResponse(res) {
res.write('</html>');
res.end();
}
/**
* Try to cast data received from update call
* @param string data input
* @return mixed casted output
* */
function castData(data) {
var tmpInt = data*1;
if (data == '') {
return ''; }
if (data == 'null') {
return null; }
if (tmpInt == data) {
return tmpInt; }
if (data == 'false') {
return false; }
if (data == 'true') {
return true; }
return data;
}
/**
* Get type of given data
* @param mixed data input
* @return string type
* */
function typeOf(data){
var type = typeof data;
if (type !== 'object') {
return type;
} else if (Object.prototype.toString.call(data) === '[object Array]') {
return 'array';
} else if (data === null) {
return 'null';
} else {
if (data instanceof Date) { return 'date'; }
return 'object';
}
}
/**
* Check if given string has mongodb object id format
* @param string data input
* @return boolean
* */
function isID(data) {
return (data.length == 12 || data.length == 24);
}
/**
* Check if edit is supported for given data
* @param mixed value data to be displayed
* @return boolean is editible?
* */
function canEditValue(value) {
var curType = typeOf(value);
return !(curType == 'array' || curType == 'object');
}
/**
* Display property value in interface
* @param mixed data data to be displayed
* @param string path absolute path for url
* @param integer index for array values
* @param object params HTTP params from request
* @return string styled value ready for output
* */
var displayValue = function(data, path, index, params) {
var curType = typeOf(data);
var curValue = data;
var curDisplay = '';
if (curType == 'array') {
var curLength = curValue.length;
curDisplay = '<table class="array">';
for (var i = 0; i < curLength; i++) {
curDisplay += '<tr><td class="desc key">' + (typeOf(data[i]) == 'array' ? '+' : '-') + ' </td><td class="content value subValue" id="">' + displayValue(data[i], path, i, params) + '</td></tr>';
}
curDisplay += '</table>';
} else if (curType == 'date') {
curDisplay = curValue;
} else if (curType == 'object') {
var hasHeadline = false;
if (curValue._id && curValue.name) {
hasHeadline = '<a href="' + path + curValue._id + '">' + curValue.name + ' (#' + curValue._id + ')</a><br />';
} else if (curValue._id) {
hasHeadline = '<a href="' + path + curValue._id + '">' + curValue._id + '</a><br />';
} else if (curValue.name) {
hasHeadline = '<a href="">' + curValue.name + '</a><br />';
}
var curDisplay = hasHeadline || '';
var objString = curValue.toString();
if (isID(objString)) {
curDisplay += '<a href="">' + objString + '</a>';
} else {
var styleString = 'display:none;';
if (!hasHeadline || hasHeadline && params.subID && params.subID == curValue._id) {
styleString = ''; }
curDisplay += '<table style="' + styleString + '" class="array">';
var count = 0;
for (var key in curValue) {
curDisplay += '<tr><td class="desc key">' + key + ':</td><td class="content value subValue" id="">' + (curValue[key]) + '</td></tr>';
}
curDisplay += '</table>';
}
} else {
curDisplay = curValue;
}
return curDisplay;
};
/**
* Start mongoclikker
* */
var funcStartMongoclikker = function() {
var app = require('express').createServer()
, express = require('express')
, Db = require('mongodb').Db
, Connection = require('mongodb').Connection
, Server = require('mongodb').Server
, BSON = require('mongodb').BSONNative
, connectionSettings = {native_parser:true}
, viewURL = '/view/'
, ConnectAuth = require(__dirname + '/lib/semu-connect-basic-auth-c32ee11/lib/basicAuth');
app.use(ConnectAuth(function (user, password) { return user === mongoclikkerConnection.auth.user && password == mongoclikkerConnection.auth.pass; }));
app.use(express.bodyParser());
if (BSON == null) {
/**
* Fallback for non-native BSON objects
* */
BSON = require('mongodb').BSONPure;
connectionSettings = {};
}
var currentDatabase = mongoclikkerConnection.db
, currentHostname = mongoclikkerConnection.host
, currentPort = mongoclikkerConnection.port;
/**
* Serve style.css file
* */
app.get('/style.css', function(req, res) {
res.end("@import url('http://fonts.googleapis.com/css?family=Varela+Round&v2'); table { -webkit-border-horizontal-spacing: 0px; -webkit-border-vertical-spacing: 0px; border-spacing: 0px; } .canEdit { cursor: pointer; } td { padding-top: 0px } .canEdit input { font-family: 'Varela Round', sans-serif; font-size: 14px; font-weight: normal; padding: 0 0 0 2px; margin: 0px; border: 0px; background-color: #CCC; } body { background-color: #EEEEEE; color: #36393D; font-family: 'Varela Round', sans-serif; font-size: 12px; font-weight: normal; margin: 30px; } a { text-decoration: none; color: #bf1010; } a:hover { text-decoration: underline; } .desc { font-weight: bold; vertical-align: top; font-size: 14px; font-weight: normal; } .content { font-size: 14px; font-weight: normal; } .content ul { list-style-type: none; margin: 0; padding: 0; } .content ul li { margin: 0; padding: 0; } .docsNav { font-size: 14px; font-weight: normal; } .docsNav td { padding-top: 15px; padding-bottom: 25px; } .key { color: #999; padding-right: 25px; } tr:hover .key { color: #36393D; } table.array td.key { padding-right: 2px; } .desc { padding-right: 25px; }");
});
/**
* Load script.js from external file
* */
app.get('/script.js', function(req, res) {
var fs = require('fs');
fs.readFile(__dirname + '/script.js', function(error, content) {
if (error) {
res.writeHead(500);
res.end(); }
else {
res.writeHead(200, { 'Content-Type': 'text/javascript' });
res.end(content, 'utf-8'); }
});
});
/**
* Redirect / to viewURL
* */
app.get('/', function(req, res) {
res.redirect(viewURL);
});
/**
* Handle ajax update calls
* */
app.post('/update/*', function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html' });
var newData = req.body.data;
var tmpProp = req.url.replace('/update/', '').split('__');
var objectFind = {'_id': tmpProp[2]};
if (tmpProp[3].length == 12 || tmpProp[2].length == 24) {
objectFind = {'_id': new BSON.ObjectID(tmpProp[2])}; }
db = new Db(tmpProp[0], new Server(currentHostname, currentPort, {}), connectionSettings)
db.open(function(err, ignored) {
if (err) { throw new Error(err); }
db.collection(tmpProp[1], function(err, collection) {
var updateKey = tmpProp[3];
var updateSet = {};
var dataType = tmpProp.pop();
updateSet[updateKey] = castData(newData, dataType);
res.write(updateSet[updateKey] + "");
res.end();
if (tmpProp[4] && tmpProp[5]) {
/**
* Update sub document
* */
/*
var subKey = tmpProp[3] + '._id';
objectFind[subKey] = tmpProp[4];
if (tmpProp[4].length == 12 || tmpProp[4].length == 24) {
objectFind[subKey] = new BSON.ObjectID(tmpProp[4]); }
var updateSubKey = tmpProp[3] + '.$.' + tmpProp[5];
var updateSet = {};
updateSet[updateSubKey] = newData;
*/
}
collection.update(objectFind, {$set: updateSet}, {safe:true},
function(err) {
if (err) console.warn(err.message);
}
);
});
});
});
/**
* Handle database access
* */
app.get(viewURL + ':curDB?/:curCollection?/:curStart?/:curLimit?/:curDocument?/:curKey?/:subID?', function(req, res, next) {
res.write('<html><head><title>mongoclikker</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script><script src="/script.js"></script><link rel="stylesheet" href="/style.css"></head>');
/**
* don't know how to get `show dbs` with node yet, so start with one datebase
* */
var dbName = req.params.curDB || currentDatabase
, listDB = [dbName]
, db = new Db(dbName, new Server(currentHostname, currentPort, {}), connectionSettings)
, path = viewURL;
res.write('<table><tr><td class="desc">database</td><td class="content"><ul id="db">');
for (var i = 0; i < listDB.length; i++) { res.write('<li><a href="' + path + listDB[i] + '">' + listDB + '</a></li>'); }
res.write('</ul></td></tr>');
if (!req.params.curDB) {
/**
* No database selected
* */
endResponse(res);
} else {
/**
* Selected database
* */
path += req.params.curDB + '/';
db.open(function(err, ignored) {
if (err) { console.log(err); }
db.collectionNames(function(err, names) {
var colItems = [];
res.write('<tr><td class="desc">collection</td><td class="content"><ul id="collection">');
for (var i = 0; i < names.length; i++) {
var tmp = names[i].name.replace(req.params.curDB + '.', '');
if (tmp.indexOf('.indexes') == -1) {
res.write('<li><a href="' + path + tmp + '/0/20">' + tmp + '</a></li>'); }
}
if (!req.params.curCollection) {
/**
* No collection selected
* */
endResponse(res);
} else {
/**
* Selected collection
* */
path += req.params.curCollection + '/' + req.params.curStart + '/' + req.params.curLimit + '/';
db.collection(req.params.curCollection, function(err, collection) {
collection.find({}, {'skip':req.params.curStart, 'limit':req.params.curLimit}).toArray(function(err, results) {
res.write('<tr><td class="desc">item</td><td class="content"><ul id="documents">');
for (var i = 0; i < results.length; i++) {
if (results[i]) { res.write('<li><a href="' + path + results[i]._id + '">' + (results[i].name && typeof(results[i].name) == 'string' ? results[i].name + ' (#' + results[i]._id + ')' : results[i]._id) + '</a></li>'); } }
res.write('</ul></td></tr>');
var prevStart = (req.params.curStart*1 - 1*req.params.curLimit);
if (prevStart < 0) {
prevStart = 0; }
if (req.params.curDocument) {
selectedItem = '/' + req.params.curDocument; }
/**
* Build navigation items
* */
var selectedItem = ''
, baseURL = viewURL + req.params.curDB + '/' + req.params.curCollection + '/'
, nextURL = baseURL + (req.params.curStart*1 + 1*req.params.curLimit) + '/' + req.params.curLimit + selectedItem
, prevURL = baseURL + prevStart + '/' + req.params.curLimit + selectedItem;
res.write('<tr class="docsNav"><td class="desc"></td><td class="content">');
if (req.params.curStart > 0) {
res.write('<a href="' + prevURL + '">prev</a> | '); }
if (results.length >= req.params.curLimit) {
res.write('<a href="' + nextURL + '">next</a></td></tr>'); }
if (!req.params.curDocument) {
/**
* No selected document
* */
res.write('</table>');
endResponse(res);
} else {
/**
* Selected document
* */
db.collection(req.params.curCollection, function(err, collection2) {
params = {'_id': req.params.curDocument};
if (req.params.curDocument.length == 12 || req.params.curDocument.length == 24) {
params = {'_id': new BSON.ObjectID(req.params.curDocument)}; }
collection.find(params).toArray(function(err, results) {
path += req.params.curDocument + '/';
for (var n in results[0]) {
/**
* Display document properties
* */
var curValue = results[0][n];
var curType = typeOf(curValue);
var curID = dbName + '__' + req.params.curCollection + '__' + req.params.curDocument + '__' + n + '__' + curType;
var curCanEdit = canEditValue(curValue);
var curKey = n;
if (curType == 'array') {
var curLength = curValue.length;
curKey = curKey + ' [' + curLength + ']';
}
curValue = displayValue(curValue, path + n + '/', 0, req.params);
res.write('<tr><td class="desc key">' + curKey + '</td><td class="content value propValue ' + (curCanEdit ? 'canEdit' : '') + '" id="' + curID + '">' + curValue + '</td></tr>');
}
res.write('</table>');
endResponse(res);
});
});
}
});
});
}
});
});
}
});
app.listen(mongoclikkerConnection.web);
console.log('Listening on port ' + mongoclikkerConnection.web);
};
exports.setHost = funcSetHost;
exports.protectWith = funcProtectWithUser;
exports.andPort = funcAndPort;
exports.withUser = funcWithUser;
exports.andPassword = funcAndPassword;
exports.forDatabase = funcforDatabase;
exports.andListenOn = exports.listenOn = funcAndListenOn;
exports.cast = castData;