-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
385 lines (347 loc) · 12.1 KB
/
app.js
File metadata and controls
385 lines (347 loc) · 12.1 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
/**
* Module dependencies.
**/
var express = require('express'),
io = require('socket.io'),
connect = require('connect'),
pageRouter = require('./routes/pageRouter'),
http = require('http'),
fs = require('fs'),
util = require('util'),
cookie = require('cookie'),
passport = require('passport'),
path = require('path'),
ObjectID = require('mongodb').ObjectID,
mongoose = require('mongoose'),
flash = require('connect-flash'),
app = express(),
os = require('os'),
childProcess = require('child_process'),
ls,
User,
db,
sharejs = require('share').server;
/**
* some middleware setup
**/
app.set('port', process.env.PORT || 3000); //sets port variable according to PORT global variable; default port=3000
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.bodyParser());
app.use(express.session({
secret: 'secret',
key: 'express.sid'
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(app.router);
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, '/public')));
/**
* creates the server
**/
var server = http.createServer(app).listen(app.get('port'), function () {
console.info('DEBUG: Server listening on port ' + app.get('port'));
console.info('DEBUG: Platform: ' + os.platform());
/**
* sets up User variable that utilizes UserSchema and sets up database connection
**/
if (os.platform() == 'win32') {
console.log('DEBUG: ' + __dirname + '/mongodb/data');
ls = childProcess.spawn(__dirname + '/mongodb/win32/mongod.exe', ['--dbpath', __dirname + '/mongodb/data']);
// ls.stdout.on('data', function (data) {
// console.log('DEBUG: db: ' + data);
// });
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
}else/** if(os.platform()=='linux'){
var chown = childProcess.spawn('sudo', ['chown','mongodb', '/mongodb/data/db'], function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
};
});
chown.stdout.on('data', function (data) {
console.log('DEBUG: chown: '+ data);
});
chown.on('close', function (code) {
console.log('child process exited with code ' + code);
});
ls = childProcess.spawn(__dirname +'/mongodb/linux/mongod', ['--dbpath', __dirname+'/mongodb/data']);
ls.stdout.on('data', function (data) {
console.log('DEBUG: db: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (code) {
console.log('child process exited with code ' + code);
});
}else**/{
console.log('DEBUG: OS support still in progress; features may be unstable');
};
setTimeout(function () {
User = mongoose.model('User', UserSchema);
mongoose.connect('mongodb://localhost/SynergyCodeCredentials'); //set connect destination as needed!!!
db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
/**
* makes sure the user collection in the database exists;
* if it doesn't, the collection is created and a default admin profile is created
**/
db.once('open', function callback() {
mongoose.connection.db.collectionNames(function (err, names) {
if (names.length == 0) {
console.log('DEBUG: Database Is Empty; Creating admin Profile');
var user = {
_id: new ObjectID(),
username: 'admin',
password: 'admin',
account_level: 'admin'
};
db.collection('users').insert(user, function callback() {
console.log('DEBUG: Admin Profile created');
});
}
});
console.log('DEBUG: Database connection successful.');
});
}, 2000);
});
/**
* Strategy and Schema declaration for database access
**/
var LocalStrategy = require('passport-local').Strategy,
Schema = mongoose.Schema,
UserSchema = new Schema({
username: String,
password: String,
account_level: String
});
var options = {db: {type: 'none'}};
sharejs.attach(app, options);
/**
* validPassword method that checks if the entered password matches the entered username
**/
UserSchema.methods.validPassword = function(pass){
if(pass == this.password){
return true;
}
return false;
}
/**
* sets up User variable that utilizes UserSchema and sets up database connection
**/
// var User = mongoose.model('User', UserSchema);
// mongoose.connect('mongodb://localhost/SynergyCodeCredentials'); //set connect destination as needed!!!
// var db = mongoose.connection;
// db.on('error', console.error.bind(console, 'connection error:'));
// /**
// * makes sure the user collection in the database exists;
// * if it doesn't, the collection is created and a default admin profile is created
// **/
// db.once('open', function callback() {
// mongoose.connection.db.collectionNames(function(err, names){
// if(names.length == 0){
// console.log('DEBUG: Database Is Empty; Creating admin Profile');
// var user = {
// _id: new ObjectID(),
// username: 'admin',
// password: 'admin',
// account_level: 'admin'
// };
// db.collection('users').insert(user, function callback(){});
// }
// });
// console.log('DEBUG: Database connection successful.');
// });
/**
* requiresLogin - allows for authentication to take place in a GET request before certain pages are accessed
**/
var requiresLogin = function(req, res, next){
if(!req.isAuthenticated()){
return res.send(400);
}
next();
}
/**
* sets up passport's strategy for verfying logins
**/
passport.use(new LocalStrategy(function(username, password, done){
User.findOne({username:username}, function(err, user){
if(err){
console.log('DEBUG: Unknown Error While Querying Database');
return done(err);
}
if(!user){
console.log('DEBUG: Incorrect Username');
return done(null, false, {message: 'Incorrect username.'});
}
if(!user.validPassword(password)){
console.log('DEBUG: Incorrect Password');
return done(null, false, {message: 'Incorrect password.'});
}
return done(null,user);
});
}));
/**
* the following methods serialize and deserialize the user on login and logout
**/
passport.serializeUser(function(user,done){
done(null, user.id);
});
passport.deserializeUser(function(id,done){
User.findById(id, function(err,user){
done(err,user);
});
});
/**
* signout - logs out the user
**/
var signout = function(req, res){
req.logout();
res.redirect('/');
}
/**
* handlers for the server's GET requests
**/
app.get('/', pageRouter.index);
app.get('/edit', requiresLogin, pageRouter.filetest);
app.get('/logout', signout);
app.get('/create', requiresLogin, pageRouter.create);
app.get('/admin', requiresLogin, function(req, res){
User.findOne({username: req.user.username}, function(err, user){
if(user.account_level == 'admin'){
res.render('adminPanel.ejs');
}else{
console.log('DEBUG: User Has Insufficient Permissions To Visit Admin Page.');
res.render('permissionProblem.ejs');
}
});
});
/**
* handles server's login requests
**/
app.post('/login',
passport.authenticate('local', {
successRedirect: '/edit',
failureRedirect: '/',
failureFlash: true
})
);
/**
* compiles a list of files in editableFsiles directory
**/
var stringHeader = "<ul class='jqueryFileTree' style='display: none;'>";
var stringFooter = "</ul>";
// arguments: path, directory name
var formatDirectory =
"<li class='directory collapsed'><a href='#' rel='%s/'>%s</a><li>";
// arguments: extension, path, filename
var formatFile = "<li class='file ext_%s'><a href='#' rel='%s'>%s</a></li>";
var createStatCallback = (function (res, path, fileName, isLast) {
return function (err, stats) {
if (stats.isDirectory()) {
res.write(util.format(formatDirectory, path, fileName));
} else {
var fileExt = fileName.slice(fileName.lastIndexOf('.') + 1);
res.write(util.format(formatFile, fileExt, path, fileName));
}
if (isLast) {
res.end(stringFooter);
}
}
});
/**
* passes the compiled list of files to file tree on front end
**/
app.post('/loadFileTree', function (req, res) {
// 'text/html'
res.writeHead(200, {
'content-type': 'text/plain'
});
res.write(stringHeader);
// get a list of files
fs.readdir(__dirname + '/public/editableFiles/', function (err, files) {
for (var i = 0; i < files.length; i++) {
var fileName = files[i];
var path = util.format('%s%s', __dirname + '/public/editableFiles/', fileName);
var isLast = (i === (files.length - 1));
var statCallback = createStatCallback(res, path, fileName, isLast);
fs.stat(path, statCallback);
}
});
});
//tells socket io to listen to our server
var sio = io.listen(server);
//sets the authorization for socket
sio.set('authorization', function (handshakeData, accept) {
if (handshakeData.headers.cookie) {
handshakeData.cookie = cookie.parse(handshakeData.headers.cookie);
handshakeData.sessionID = connect.utils.parseSignedCookie(handshakeData.cookie['express.sid'], 'secret');
if (handshakeData.cookie['express.sid'] == handshakeData.sessionID) {
return accept('Cookie is invalid.', false);
}
} else {
return accept('No cookie transmitted.', false);
}
accept(null, true);
});
/**
* handles socket requests from front end
**/
sio.sockets.on('connection', function (socket) {
//sends welcome message to chat
socket.emit('message', {
message: 'Welcome to the chat!'
});
//this handles the chat
socket.on('send', function (data) {
sio.sockets.emit('message', data);
});
//loads a file into the editor
socket.on('fileLoad', function (data) {
filePath = data.message;
fileNameArray = filePath.split("/");
fileName = fileNameArray[fileNameArray.length - 1];
fs.readFile(__dirname + '/public/editableFiles/' + fileName, "utf8", function (err, data) {
if (err) {
console.log(err);
throw err;
}
socket.emit('fileData', {
message: data
});
});
console.log('DEBUG: File Loaded');
});
//saves files to editableFiles directory
socket.on('fileChanged', function (data) {
fs.writeFile('public/editableFiles/' + fileName, data.message, function (err) {
if (err) {
throw err;
}
console.log('fileChanged event received on server');
});
});
//creates a new file in editableFiles directory
socket.on('createFile', function (data) {
fs.writeFile('public/editableFiles/' + data.message, "", function (err) {
if (err) {
throw err;
}
console.log('DEBUG: File Created');
});
});
});