forked from mongo-express/mongo-express
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
321 lines (257 loc) · 8.56 KB
/
app.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
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, http = require('http');
var _ = require('underscore');
var async = require('async');
var utils = require('./utils');
var mongodb = require('mongodb');
var cons = require('consolidate');
var swig = require('swig');
var swigFilters = require('./filters');
var app = express();
var config = require('./config');
//Set up swig
app.engine('html', cons.swig);
Object.keys(swigFilters).forEach(function (name) {
swig.setFilter(name, swigFilters[name]);
});
//App configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'html');
app.set('view options', {layout: false});
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(config.site.baseUrl,express.static(__dirname + '/public'));
app.use(express.bodyParser());
app.use(express.cookieParser(config.site.cookieSecret));
app.use(express.session({
secret: config.site.sessionSecret,
key: config.site.cookieKeyName
}));
app.use(express.methodOverride());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler());
});
//Set up database stuff
var host = config.mongodb.server || 'localhost';
var port = config.mongodb.port || mongodb.Connection.DEFAULT_PORT;
var dbOptions = {
auto_reconnect: config.mongodb.autoReconnect,
poolSize: config.mongodb.poolSize
};
var db = new mongodb.Db('local', new mongodb.Server(host, port, dbOptions));
var connections = {};
var databases = [];
var collections = {};
var adminDb;
var mainConn; //main db connection
//Update the collections list
var updateCollections = function(db, dbName, callback) {
db.collectionNames(function (err, result) {
var names = [];
for (var r in result) {
var coll = utils.parseCollectionName(result[r].name);
names.push(coll.name);
}
collections[dbName] = names.sort();
if (callback) {
callback(err);
}
});
};
//Update database list
var updateDatabases = function(admin) {
admin.listDatabases(function(err, dbs) {
if (err) {
//TODO: handle error
console.error(err);
}
for (var key in dbs.databases) {
var dbName = dbs.databases[key]['name'];
//'local' is special database, ignore it
if (dbName == 'local') {
continue;
}
if (config.mongodb.whitelist.length != 0) {
if (!_.include(config.mongodb.whitelist, dbName)) {
continue;
}
}
if (config.mongodb.blacklist.length != 0) {
if (_.include(config.mongodb.blacklist, dbName)) {
continue;
}
}
connections[dbName] = mainConn.db(dbName);
databases.push(dbName);
updateCollections(connections[dbName], dbName);
}
//Sort database names
databases = databases.sort();
});
};
//Connect to mongodb database
db.open(function(err, db) {
if (err) {
throw err;
}
console.log('Database connected!');
mainConn = db;
//Check if admin features are on
if (config.mongodb.admin === true) {
//get admin instance
db.admin(function(err, a) {
adminDb = a;
if (config.mongodb.adminUsername.length == 0) {
console.log('Admin Database connected');
updateDatabases(adminDb);
} else {
//auth details were supplied, authenticate admin account with them
adminDb.authenticate(config.mongodb.adminUsername, config.mongodb.adminPassword, function(err, result) {
if (err) {
//TODO: handle error
console.error(err);
}
console.log('Admin Database connected');
updateDatabases(adminDb);
});
}
});
} else {
//Regular user authentication
if (typeof config.mongodb.auth == "undefined" || config.mongodb.auth.length == 0) {
throw new Error('Add auth details to config or turn on admin!');
}
async.forEachSeries(config.mongodb.auth, function(auth, callback) {
console.log("Connecting to " + auth.database + "...");
connections[auth.database] = mainConn.db(auth.database);
databases.push(auth.database);
if (typeof auth.username != "undefined" && auth.username.length != 0) {
connections[auth.database].authenticate(auth.username, auth.password, function(err, success) {
if (err) {
//TODO: handle error
console.error(err);
}
if (!success) {
console.error('Could not authenticate to database "' + auth.database + '"');
}
updateCollections(connections[auth.database], auth.database);
console.log('Connected!');
callback();
});
} else {
updateCollections(connections[auth.database], auth.database);
console.log('Connected!');
callback();
}
});
}
});
//View helper, sets local variables used in templates
app.all('*', function(req, res, next) {
res.locals.baseHref = config.site.baseUrl;
res.locals.databases = databases;
res.locals.collections = collections;
//Flash messages
if (req.session.success) {
res.locals.messageSuccess = req.session.success;
delete req.session.success;
}
if (req.session.error) {
res.locals.messageError = req.session.error;
delete req.session.error;
}
return next();
});
//route param pre-conditions
app.param('database', function(req, res, next, id) {
//Make sure database exists
if (!_.include(databases, id)) {
req.session.error = "Database not found!";
return res.redirect(config.site.baseUrl);
}
req.dbName = id;
res.locals.dbName = id;
if (connections[id] !== undefined) {
req.db = connections[id];
} else {
connections[id] = mainConn.db(id);
req.db = connections[id];
}
next();
});
//:collection param MUST be preceded by a :database param
app.param('collection', function(req, res, next, id) {
//Make sure collection exists
if (!_.include(collections[req.dbName], id)) {
req.session.error = "Collection not found!";
return res.redirect(config.site.baseUrl+'db/' + req.dbName);
}
req.collectionName = id;
res.locals.collectionName = id;
connections[req.dbName].collection(id, function(err, coll) {
if (err || coll == null) {
req.session.error = "Collection not found!";
return res.redirect(config.site.baseUrl+'db/' + req.dbName);
}
req.collection = coll;
next();
});
});
//:document param MUST be preceded by a :collection param
app.param('document', function(req, res, next, id) {
if (id.length == 24) {
//Convert id string to mongodb object ID
try {
id = new mongodb.ObjectID.createFromHexString(id);
} catch (err) {
}
}
req.collection.findOne({_id: id}, function(err, doc) {
if (err || doc == null) {
req.session.error = "Document not found!";
return res.redirect(config.site.baseUrl+'db/' + req.dbName + '/' + req.collectionName);
}
req.document = doc;
res.locals.document = doc;
next();
});
});
//mongodb middleware
var middleware = function(req, res, next) {
req.adminDb = adminDb;
req.databases = databases; //List of database names
req.collections = collections; //List of collection names in all databases
//Allow page handlers to request an update for collection list
req.updateCollections = updateCollections;
next();
};
//Routes
app.get(config.site.baseUrl, middleware, routes.index);
app.get(config.site.baseUrl+'db/:database/:collection/:document', middleware, routes.viewDocument);
app.put(config.site.baseUrl+'db/:database/:collection/:document', middleware, routes.updateDocument);
app.del(config.site.baseUrl+'db/:database/:collection/:document', middleware, routes.deleteDocument);
app.post(config.site.baseUrl+'db/:database/:collection', middleware, routes.addDocument);
app.get(config.site.baseUrl+'db/:database/:collection', middleware, routes.viewCollection);
app.put(config.site.baseUrl+'db/:database/:collection', middleware, routes.renameCollection);
app.del(config.site.baseUrl+'db/:database/:collection', middleware, routes.deleteCollection);
app.post(config.site.baseUrl+'db/:database', middleware, routes.addCollection);
app.get(config.site.baseUrl+'db/:database', middleware, routes.viewDatabase);
//run as standalone App?
if (require.main === module){
app.listen(config.site.port);
console.log("Mongo Express server listening on port " + (config.site.port || 80));
}else{
//as a module
console.log('Mongo Express module ready to use on route "'+config.site.baseUrl+'*"');
server=http.createServer(app);
module.exports=function(req,res,next){
server.emit('request', req, res);
};
}