This repository has been archived by the owner on Jul 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
303 lines (235 loc) · 10.6 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
'use strict';
/* ---------------------------------------------------------------------------------------------- */
// Dependencies
/* ---------------------------------------------------------------------------------------------- */
var express = require('express'),
path = require('path'),
fs = require('fs'),
mongoose = require('mongoose'),
MongoStore = require('connect-mongo-store')(express),
async = require('async'),
passport = require('passport'),
passportSocketIo = require("passport.socketio"),
socketio = require('socket.io'),
http = require('http'),
useragent = require('express-useragent');
/* ---------------------------------------------------------------------------------------------- */
// Setup
/* ---------------------------------------------------------------------------------------------- */
// Express
var app = express(),
server = http.createServer(app);
// Connect to database
var db = require('./lib/db/mongo');
// Setup Socket.io
var io = socketio.listen(server);
/* ---------------------------------------------------------------------------------------------- */
// Setup Passport-Local Authentatication
/* ---------------------------------------------------------------------------------------------- */
var LocalStrategy = require('passport-local').Strategy;
passport.serializeUser(function(user, done) {
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
mongoose.model('User')
.findById(id, function (err, user) {
done(err, user);
});
});
passport.use(new LocalStrategy({passReqToCallback: true},function(req, username, password, done) {
mongoose.model('User').findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) { return done(null, false, { message: 'Unknown user ' + username }); }
user.comparePassword(password, function(err, isMatch) {
if (err) return done(err);
if(isMatch) {
if (req.body.rememberme === true) {
req.session.cookie.expires = false;
}
return done(null, user);
} else {
return done(null, false, { message: 'Invalid password' });
}
});
});
}));
passportSocketIo.forEachAuthedSocket = function (callback) {
this.filterSocketsByUser(io, function (user) {
return user.logged_in === true;
})
.forEach(function (socket) {
if (callback && typeof(callback) === 'function') {
callback(socket);
}
});
};
/* ---------------------------------------------------------------------------------------------- */
// MongoStore Session Storage Configuration
/* ---------------------------------------------------------------------------------------------- */
var uristring =
process.env.MONGOLAB_URI ||
process.env.MONGOHQ_URL ||
'mongodb://localhost/blimp-io';
var mongoOptions = { db: { safe: true } };
var mongoStore = new MongoStore(uristring, mongoOptions);
mongoStore.on('connect', function() {
console.log('mongoStore is ready to use')
})
mongoStore.on('error', function(err) {
console.log('mongoStore Error: ', err)
})
/* ---------------------------------------------------------------------------------------------- */
// SocketIO Configuration
/* ---------------------------------------------------------------------------------------------- */
io.configure(function () {
io.set('authorization', passportSocketIo.authorize({
cookieParser: express.cookieParser,
key: 'connect.sid', // the name of the cookie where express/connect stores its session_id
secret: 'vI0GO63jD4%IjP0tagBeW4&5pTOqQo!x', // the session_secret to parse the cookie
store: mongoStore, // we NEED to use a sessionstore. no memorystore please
success: onAuthorizeSuccess, // *optional* callback on success - read more below
fail: onAuthorizeFail, // *optional* callback on fail/error - read more below
}));
});
function onAuthorizeSuccess(data, accept){
console.log('successful connection to socket.io');
// The accept-callback still allows us to decide whether to
// accept the connection or not.
accept(null, true);
}
function onAuthorizeFail(data, message, error, accept){
/*if(error) {
throw new Error(message);
}*/
console.log('failed connection to socket.io:', message);
// We use this callback to log all of our failed connections.
accept(null, true);
}
/* ---------------------------------------------------------------------------------------------- */
// Express Configuration
/* ---------------------------------------------------------------------------------------------- */
app.configure(function(){
app.use(useragent.express());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.compress());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({ store: mongoStore, secret: 'vI0GO63jD4%IjP0tagBeW4&5pTOqQo!x' }))
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
app.configure('development', function(){
app.use(express.logger('dev'));
app.use(express.static(path.join(__dirname, '.tmp')));
app.use(express.static(path.join(__dirname, 'app')));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.favicon(path.join(__dirname, 'public/favicon.ico')));
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 60 * 60 * 24 * 365 * 10 }));
});
/* ---------------------------------------------------------------------------------------------- */
// Mongoose Models
/* ---------------------------------------------------------------------------------------------- */
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
mongoose.plugin(function(schema, opts) {
schema.statics.isObjectId = function(id) {
if(id) {
return checkForHexRegExp.test(id);
}
return false;
};
});
var modelsPath = path.join(__dirname, 'lib/models');
fs.readdirSync(modelsPath)
.forEach(function (file) {
require(modelsPath + '/' + file)(mongoose);
});
/* ---------------------------------------------------------------------------------------------- */
// Auth Routes
/* ---------------------------------------------------------------------------------------------- */
app.get('/api/loggedin', function(req, res) {
if (req.isAuthenticated && req.user) {
res.send({
username: req.user.username,
email: req.user.email
});
} else {
res.send('0');
}
});
app.post('/api/login', function(req, res) {
passport.authenticate('local', function(err, user, info) {
if (err) { return res.send({'status':'err','message':err.message}); }
if (!user) { return res.send({'status':'fail','message':info.message}); }
req.logIn(user, function(err) {
if (err) { return res.send({'status':'err','message':err.message}); }
return res.send({'status':'ok'});
});
})(req, res);
});
app.post('/api/logout', function(req, res){
req.session.destroy(function (err) {
res.send(200);
});
});
var auth = function (req, res, next) {
if (req.isAuthenticated()) {
return next();
}
res.send(401);
};
/* ---------------------------------------------------------------------------------------------- */
// Controllers
/* ---------------------------------------------------------------------------------------------- */
var api = {
blimps: require('./lib/controllers/blimps')(mongoose, async, io, passportSocketIo),
reports: require('./lib/controllers/reports')(mongoose, async, io, passportSocketIo),
users: require('./lib/controllers/users')(mongoose, async, io, passportSocketIo)
};
/* ---------------------------------------------------------------------------------------------- */
// Routes
/* ---------------------------------------------------------------------------------------------- */
app.get( '/api/blimps', auth, api.blimps.findAll);
app.get( '/api/blimps/:bid', auth, api.blimps.find);
app.post( '/api/blimps', auth, api.blimps.createNew);
app.put( '/api/blimps/:bid', auth, api.blimps.update);
app.delete( '/api/blimps/:bid', auth, api.blimps.delete);
app.post( '/api/reports', api.reports.createNew);
app.get( '/api/reports', auth, api.reports.findAll);
app.get( '/api/reports/:logid', auth, api.reports.findById);
app.get( '/api/blimps/:bid/reports', auth, api.reports.findAllByBlimp);
app.get( '/api/users', auth, api.users.findAll);
app.get( '/api/users/:userid', auth, api.users.findById);
app.post( '/api/users', auth, api.users.createNew);
app.put( '/api/users/:userid', auth, api.users.updateById);
app.delete( '/api/users/:userid', auth, api.users.deleteById);
/* ---------------------------------------------------------------------------------------------- */
// Start server
/* ---------------------------------------------------------------------------------------------- */
var port = process.env.PORT || 9007;
server.listen(port, function () {
var UserModel = mongoose.model('User');
UserModel.count(function (err, count) {
if (!err && count === 0) {
console.log('No Users Found! \nCreating default user blimp/blimp .....');
UserModel.create(
{
username : 'blimp',
email : '[email protected]',
password : 'blimp'
},
function(err) {
if (!err) {
console.log('Success: Default user created!');
} else {
console.log('Error: Creating default user failed!')
}
}
);
}
});
console.log('The express server listening on port %d in %s mode', port, app.get('env'));
});