-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
325 lines (279 loc) · 9.75 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
var util = require('util');
var _ = require('underscore');
var http = require('http');
var url = require('url');
var express = require('express');
var io = require('socket.io');
var ConnectCouchdb = require('connect-couchdb')(express);
var auth = require('./server/auth').auth;
var config = require('./server/config').config;
var sessionStore = new ConnectCouchdb({
name: 'cgip_user_sessions',
username: config.adminName,
password: config.adminPassword,
host: config.databaseHost,
port: config.databasePort
});
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('./server/models/user').User;
var Actor = require('./server/models/actor').Actor;
var Connection = require('./server/models/connection').Connection;
var Country = require('./server/models/country').Country;
var app = express();
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
},
auth.authenticate));
passport.serializeUser(auth.serializeUser);
passport.deserializeUser(auth.deserializeUser);
app.configure(function(){
app.set('view engine', 'jade');
app.set('views', __dirname + '/server/views');
app.set('view options', {
layout: false
});
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.favicon());
app.use(express.static(__dirname + '/public'));
app.use(express.session({
store: sessionStore,
key: 'cgipsid',
secret: config.sessionSecret,
cookie: {
maxAge: 604800000
}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.csrf());
app.use(function(req, res, next) {
res.locals.csrf_token = function(){ return req.session._csrf; };
next();
});
app.use(app.router);
});
/** Performs general routing actions */
var routeHandler = {
/** Simply renders the index */
renderIndex: function(req, res){
res.render('index', { user: (req.user || null), lockedModels: lockedModels});
},
/** Redirects to the login when the user is not logged in */
checkLogin: function(req, res){
if(req.user){
var user = {};
user._id = req.user.id;
user._rev = req.user._rev;
res.render('index', { user: user, lockedModels: lockedModels});
}else{
res.redirect('/login?forward_to=' + req.url.split('/').join('__'));
}
},
/** Redirects the user when already logged in */
redirectWhenLoggedIn: function(req, res){
if(req.user){
res.redirect('/edit');
}else{
res.render('index', { user: null, lockedModels: lockedModels});
}
},
/** Returns an error when the requested model is locked */
failIfModelLocked: function(req, res, next){
var id = req.params.actor_id || req.params.connection_id;
var alreadyLocked = _.find(lockedModels, function(locked){ return locked.model_id == id; });
// Model already locked by another user
if(alreadyLocked && req.user._id != alreadyLocked.user_id){
res.json({error: 'Model is locked'}, 423);
}else{
next();
}
}
};
/* Push state URLs */
app.get('/', routeHandler.renderIndex);
app.get('/show/:country', routeHandler.renderIndex);
app.get('/login', routeHandler.redirectWhenLoggedIn);
app.get('/edit', routeHandler.checkLogin);
app.get('/edit/countries', routeHandler.checkLogin);
app.get('/edit/:country', routeHandler.checkLogin);
app.get('/edit/:country/actors', routeHandler.checkLogin);
app.get('/edit/:country/money/list', routeHandler.checkLogin);
app.get('/import/:country/money', routeHandler.checkLogin);
/* Session / auth handling */
app.post('/session', passport.authenticate('local'), function(req, res){
res.json({_id: req.user._id, _rev: req.user._rev});
});
app.del('/session', function(req, res){
req.logout();
req.session.destroy(function(){
res.json({ ok: true });
});
});
app.get('/logout', function(req, res){
req.logout();
req.session.destroy(function(){
res.redirect('/edit');
});
});
/* Actor CRUD */
app.get('/:country/actors', function(req, res){
Actor.allByCountry(req.params.country, function(err, docs){
if(err) return res.json(err, 404);
res.json(docs);
});
});
app.post('/:country/actors', auth.ensureAuthenticated, function(req, res){
Actor.create(req.body, function(err, actor){
if(err) return res.json(err, 404);
res.json(actor);
});
});
app.put('/:country/actors/:actor_id', auth.ensureAuthenticated, routeHandler.failIfModelLocked, function(req, res){
Actor.edit(req.params.actor_id, req.body, function(err, actor){
if(err)
if(err.error == 'conflict') return res.json(err, 409); // conflict
else return res.json(err, 404); // not found
io.sockets.emit('change:' + req.params.actor_id, actor);
res.json(actor);
});
});
app.del('/:country/actors/:actor_id', auth.ensureAuthenticated, routeHandler.failIfModelLocked, function(req, res){
Actor.remove(req.params.actor_id, function(err, actor){
io.sockets.emit('destroy:' + req.params.actor_id, actor);
res.json(actor);
});
});
/* Connections CRUD */
app.get('/:country/connections', function(req, res){
Connection.allByCountry(req.params.country, function(err, docs){
if(err) return res.json(err, 404);
res.json(docs);
});
});
app.get('/:country/connections/:connection_type', function(req, res){
Connection.allByCountryAndType(req.params.country, req.params.connection_type, function(err, docs){
if(err) return res.json(err, 404);
res.json(docs);
});
});
app.post('/:country/connections', auth.ensureAuthenticated, function(req, res){
Connection.create(req.body, function(err, connection){
if(err) return res.json(err, 404);
res.json(connection);
});
});
app.put('/:country/connections/:connection_id', auth.ensureAuthenticated, routeHandler.failIfModelLocked, function(req, res){
Connection.edit(req.params.connection_id, req.body, function(err, connection){
if(err)
if(err.error == 'conflict') return res.json(err, 409); // conflict
else return res.json(err, 404); // not found
io.sockets.emit('change:' + req.params.connection_id, connection);
res.json(connection);
});
});
app.del('/:country/connections/:connection_id', auth.ensureAuthenticated, routeHandler.failIfModelLocked, function(req, res){
Connection.remove(req.params.connection_id, function(err, connection){
io.sockets.emit('destroy:' + req.params.connection_id, null);
res.json(connection);
});
});
app.post('/:country/connections/:connection_type/destroyAll', auth.ensureAuthenticated, function(req, res){
var models = req.body.models || [];
if(models.length > 0)
Connection.removeAll(req.body.models, function(err, con){
if(err) return res.json(err, 404);
res.json({ ok: true });
});
else
res.json({ ok: true });
});
// Countries CRUD
app.get('/countries', function(req, res){
Country.all(function(err, docs){
if(err) return res.json(err, 404);
res.json(docs);
});
});
app.post('/countries', auth.ensureAuthenticated, function(req, res){
Country.create(req.body, function(err, country){
if(err) return res.json(err, 404);
res.json(country);
});
});
app.del('/countries/:id', auth.ensureAuthenticated, function(req, res){
Country.remove(req.params.id, function(err, country){
if(err) return res.json(err, 404);
res.json(country);
});
});
app.put('/countries/:id', auth.ensureAuthenticated, function(req, res){
Country.edit(req.params.id, req.body, function(err, country){
if(err) return res.json(err, 404);
res.json(country);
});
});
var port = process.env.APP_PORT || 3000;
var server = app.listen(port);
console.log('Server is up and running on port: ' + port);
var lockedModels = [];
// Realtime stuff
var io = io.listen(server);
// a less noisy log level
io.set('log level', 1)
// new connection established
io.sockets.on('connection', function (socket) {
// register the current user
socket.on('register_socket', function (user_id) {
socket.user_id = user_id;
console.log('register socket', user_id);
});
// broadcast a lock for a model
socket.on('lock', function(model_id){
var lock = {
user_id: socket.user_id,
model_id: model_id
};
// don't allow to lock models that are already locked
var alreadyLocked = _.find(lockedModels, function(locked){ return locked.model_id == model_id; });
if(alreadyLocked) return;
lockedModels.push(lock);
socket.broadcast.emit('lock', model_id);
socket.broadcast.emit('lock:'+model_id, null);
});
// broadcast an unlock for a model
socket.on('unlock', function(model_id){
lockedModels = _.reject(lockedModels, function(model){ return model.model_id == model_id; });
socket.broadcast.emit('unlock', model_id);
socket.broadcast.emit('unlock:'+model_id, null);
});
socket.on('new_model', function(model){
var country = model.country;
var type = model.type;
var specificType = (type == 'actor') ? model['actorType'] : model['connectionType'];
var key = [country, type].join(':');
if(specificType)
key += ':' + specificType;
socket.broadcast.emit(key, model);
});
socket.on('moveToGroup', function(actor_id){
socket.broadcast.emit('moveToGroup:' + actor_id);
});
socket.on('disconnect', function(){
var user_id = socket.user_id;
console.log('disconnect socket', user_id);
// select all tha locked models from this user
var user_models = _.where(lockedModels, { user_id: user_id });
// broadcast unlocks for these models
_.each(user_models, function(model){
var model_id = model.model_id;
socket.broadcast.emit('unlock', model_id);
socket.broadcast.emit('unlock:'+model_id, null);
});
// delete the locks
lockedModels = _.reject(lockedModels, function(model){ return model.user_id == user_id; });
});
});