-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.js
More file actions
710 lines (573 loc) · 21.8 KB
/
Copy pathserver.js
File metadata and controls
710 lines (573 loc) · 21.8 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
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/*
Module dependencies:
- Express
- Http (to run Express)
- Body parser (to parse JSON requests)
It is a common practice to name the variables after the module name.
Ex: http is the "http" module, express is the "express" module, etc.
*/
var express = require("express")
, bodyParser = require("body-parser");
var path = require('path');
var morgan = require('morgan');
var app = require('./ApplicationInstance');
var passport = require('passport');
// var mongoose = require('mongoose'); MOngo Connection failure aws
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var configDB = require('./backend/Models/database.js');
var http = require("http").createServer(app);
var compression = require('compression');
var connection = require('./backend/Models/db_model.js')
// var connection2 = require('./backend/Models/db_Model2.js')
//var mainRoutes = require(__dirname+'/backend/routes/MainRoutes');
var _ = require("underscore");
var io = require("socket.io").listen(http);
var bcrypt = require('bcrypt-nodejs');
var salt = bcrypt.genSaltSync(10);
var User = require('./backend/Models/user1.js')
//configuration ===============================================
// configuration ===============================================================
// mongoose.connect(configDB.url); // connect to our database MOngo Connection failure aws
// require('./backend/Models/passport')(passport); // pass passport for configuration
//================ Server config ================================
//Server's IP address
// app.set("ipaddr", process.env.IP || "127.0.0.1" );
//Server's port number
app.set("port", process.env.PORT || 4000);
//
// var ChatSchema = mongoose.Schema({
// created: Date,
// content: String,
// username: String,
// room: String
// }); MOngo Connection failure aws
// var Chat = mongoose.model('Chat',ChatSchema); MOngo Connection failure aws
app.all('*',function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-type,Accept,X-Access-Token,X-Key');
if (req.method == 'OPTIONS') {
res.status(200).end();
} else {
next();
}
});
/*
The list of participants in our chatroom.
The format of each participant will be:
{
id: "sessionId",
name: "participantName"
}
*/
var participants = [];
var usernum =0;
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
//app.use(bodyParser()); // get information from html forms
app.use(compression());
app.use(express.static(path.resolve(__dirname,'client/public')));
app.set('views',__dirname + '/client/views');
app.engine('html',require('ejs').renderFile);
app.set("view engine", "ejs");
//app.use(express.static("public",__dirname + '/client/public'));
//Tells server to support JSON requests
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// required for passport
app.use(session({ secret: 'letthegamebegins' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
var rooms=0;
function newRoom(room,chatstring){
var query = 'SELECT `email` from `links` where `link` = ?'
connection.query(query,chatstring,function(err,results,fields){
if(results===undefined)
{
return null;
}
else if(Object.keys(results).length===0){
return null;
}
else{
return createTable2(results[0],room);
}
});
}
function createTable2(room){
var query = 'Create TABLE IF NOT EXISTS `'+email+'` ( `room` INT(32) NOT NULL) ENGINE = InnoDB;'
connection2.query(query,function(err,results,fields){
connection2.query('SELECT `room` from '+email+' where `room` = ?',room,function(err,results,fields){
if(Object.keys(results).length==0){
connection2.query('INSERT INTO `'+email+'` `room` values '+room,function(err,results,fields){
console.log("done");
})
}
})
});
}
function createTable(chatstring,id,res){
var query = 'CREATE TABLE IF NOT EXISTS `'+chatstring+'` ( `id` INT(32) NOT NULL , `roomnum` INT(32) NOT NULL) ENGINE = InnoDB;'
connection.query(query,function(err,results,fields){
getid(chatstring,id,res);
})
}
function getid(chatstring,id,res){
var query = 'SELECT `roomnum` from '+chatstring+' where `id`= ?';
connection.query(query,id,function(err,results,fields){
console.log(results);
if(results===undefined)
{
console.log("in if"+rooms)
connection.query('INSERT INTO `'+chatstring+'` (`id` ,`roomnum`) values ('+id+' ,'+rooms+')',function(err,results,fields){
console.log("in if connection"+rooms);
rooms++;
newRoom(rooms-1,chatstring);
res.json(rooms-1);
});
}
else if(Object.keys(results).length==0){
console.log("in else if"+rooms)
connection.query('INSERT INTO `'+chatstring+'` (`id` ,`roomnum`) values ('+id+' ,'+rooms+')',function(err,results,fields){
console.log("in else if connection"+rooms);
rooms++;
newRoom(rooms-1,chatstring);
res.json(rooms-1);
});
}
else
{
console.log("results here"+id);
res.json(results[0].roomnum);
}
})
}
function getRoomNo(chatstring){
// extract room no from String
return chatstring;
}
/* Server routing */
//app.use('/',mainRoutes);
//=================================================================
// ========== Routes =================================
//==============================================================
//Handle route "GET /", as in "http://localhost:8080/"
/*app.get("/", function(request, response) {
//Render the view called "index"
response.render("index");
});
app.get("/admin",function(req,res) {
res.render("admin/admin")
});
//POST method to create a chat message
app.post("/message", function(request, response) {
//The request body expects a param named "message"
var message = request.body.message;
//If the message is empty or wasn't sent it's a bad request
if(_.isUndefined(message) || _.isEmpty(message.trim())) {
return response.json(400, {error: "Message is invalid"});
}
//We also expect the sender's name with the message
var name = request.body.name;
//Let our chatroom know there was a new message
io.sockets.emit("incomingMessage", {message: message, name: name});
//Looks good, let the client know
response.json(200, {message: "Message received"});
});*/
// normal routes ===============================================================
// show the home page (will also have our login links)
app.get('/', function(req, res) {
res.render('index.ejs');
});
app.get('/auth',function(req,res){
res.render('auth.ejs')
})
// PROFILE SECTION =========================
app.get('/profile', isLoggedIn, function(req, res) {
res.render('profile.ejs', {
user : req.user
});
});
app.get('/admin',function(req,res,next){
if(sessionChecker1(req,res,next)){
res.render('admin/admin.ejs');
}
})
app.post('/listing',function(req,res){
console.log(req.session.user.email);
connection2.query('CREATE TABLE IF NOT EXISTS `'+req.session.user.email+'` ( `room` INT(32) NOT NULL) ENGINE = InnoDB;',function(err,results,fields){
connection2.query('SELECT * from `'+req.session.user.email+'`',function(err,results,fields){
if(err) throw err;
results = parseIt(results);
//console.log(result);
return res.json(results);
})
})
});
function parseIt(rawData){
rawData = JSON.stringify(rawData);
rawData = JSON.parse(rawData);
return rawData;
}
app.use(session({
key:'user_sid',
secret: 'letthegamebegins',
resave:false,
saveUninitialized:false,
cookie:{
expires:600000
}
}));
app.use((req, res, next) => {
if (req.cookies.user_sid && !req.session.user) {
res.clearCookie('user_sid');
}
next();
});
var sessionChecker1 = (req,res,next) => {
console.log(req.cookies);
console.log(req.session);
if(req.session.user) {
return true;
}
else
{
res.redirect('/');
}
};
var sessionChecker = (req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
console.log(req.session.user);
res.redirect('/admin');
} else {
next();
}
};
app.use(function (req, res, next) {
// check if client sent cookie
var cookie = req.cookies.cookieName;
if (cookie === undefined)
{
// no: set a new cookie
var randomNumber=Math.random().toString();
randomNumber=randomNumber.substring(2,randomNumber.length);
usernum++;
res.cookie('cookieName',usernum, { maxAge: 900000, httpOnly: false });
console.log('cookie created successfully');
}
else
{
// yes, cookie was already present
console.log('cookie exists', cookie);
}
next(); // <-- important!
});
// LOGOUT ==============================
app.get('/logout', (req, res) => {
if (req.session.user && req.cookies.user_sid) {
res.clearCookie('user_sid');
res.redirect('/');
} else {
res.redirect('/auth');
}
});
// return a random string to be used
var count = 0;
app.post("/getrandomid", function(req,res){
var value = bcrypt.hashSync(count,salt);
count++;
res.send(value);
});
//
var chatrouter = require('express').Router();
app.use('/randomChats/',chatrouter);
chatrouter.route('/:chatstring').get(function(req,res){
roomNo = getRoomNo(req.params.chatstring);
res.render('anonymous/anonymous.ejs',{chatstring:req.params.chatstring});
// res.send(req.params.chatstring);
});
app.post("/getroom", function(req, res) {
// console.log(req);
createTable(req.body.chatstring,req.body.id,res)
});
app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/profile',
failureRedirect : '/'
}));
app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
// the callback after google has authenticated the user
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/profile',
failureRedirect : '/'
}));
// =============================================================================
// AUTHENTICATE (FIRST LOGIN) ==================================================
// =============================================================================
// locally --------------------------------
// LOGIN ===============================
// show the login form
app.route('/login')
.get(sessionChecker,(req, res) =>{
res.render('login.ejs', { message: '' });
})
.post((req,res) =>{
var email = req.body.email,
password = req.body.password;
User.findOne({ where: { email: email } }).then(function (user) {
if (!user) {
res.render('login.ejs',{
user: null,
message: 'User does not exit'
});
} else if (!user.validPassword(password)) {
res.render('login.ejs',{
user: null,
message: 'Oops! wrong password'
});
}
else {
req.session.user = user.dataValues;
res.redirect('/admin');
}
});
})
app.route('/signup')
.get(sessionChecker, (req, res) => {
res.render('signup.ejs',{
user:req.session.user,
message: ''
});
})
.post((req, res) => {
User.create({
email: req.body.email,
password: req.body.password
})
.then(user => {
req.session.user = user.dataValues;
// checkEmail(req.session.user.email);
res.redirect('/admin');
})
.catch(error => {
console.log(error);
res.render('login.ejs',{
user: null,
message: 'Email id is already in use'
});
});
});
// process the login form
// app.post('/login', passport.authenticate('local-login', {
// successRedirect : '/admin', // redirect to the secure profile section
// failureRedirect : '/login', // redirect back to the signup page if there is an error
// failureFlash : true // allow flash messages
// }));
// SIGNUP =================================
// show the signup form
// app.get('/signup', function(req, res) {
// res.render('signup.ejs', { message: req.flash('signupMessage') });
// });
// // process the signup form
// app.post('/signup', passport.authenticate('local-signup', {
// successRedirect : '/admin', // redirect to the secure profile section
// failureRedirect : '/signup', // redirect back to the signup page if there is an error
// failureFlash : true // allow flash messages
// }));
// facebook -------------------------------
// send to facebook to do the authentication
app.get('/auth/facebook', passport.authenticate('facebook', { scope : 'email' }));
// handle the callback after facebook has authenticated the user
app.get('/auth/facebook/callback',
passport.authenticate('facebook', {
successRedirect : '/admin',
failureRedirect : '/'
}));
// twitter --------------------------------
// send to twitter to do the authentication
app.get('/auth/twitter', passport.authenticate('twitter', { scope : 'email' }));
// handle the callback after twitter has authenticated the user
app.get('/auth/twitter/callback',
passport.authenticate('twitter', {
successRedirect : '/admin',
failureRedirect : '/'
}));
// google ---------------------------------
// send to google to do the authentication
app.get('/auth/google', passport.authenticate('google', { scope : ['profile', 'email'] }));
// the callback after google has authenticated the user
app.get('/auth/google/callback',
passport.authenticate('google', {
successRedirect : '/admin',
failureRedirect : '/'
}));
// =============================================================================
// AUTHORIZE (ALREADY LOGGED IN / CONNECTING OTHER SOCIAL ACCOUNT) =============
// =============================================================================
// locally --------------------------------
app.get('/connect/local', function(req, res) {
res.render('connect-local.ejs', { message: req.flash('loginMessage') });
});
app.post('/connect/local', passport.authenticate('local-signup', {
successRedirect : '/admin', // redirect to the secure profile section
failureRedirect : '/connect/local', // redirect back to the signup page if there is an error
failureFlash : true // allow flash messages
}));
// facebook -------------------------------
// send to facebook to do the authentication
app.get('/connect/facebook', passport.authorize('facebook', { scope : 'email' }));
// handle the callback after facebook has authorized the user
app.get('/connect/facebook/callback',
passport.authorize('facebook', {
successRedirect : '/admin',
failureRedirect : '/'
}));
// twitter --------------------------------
// send to twitter to do the authentication
app.get('/connect/twitter', passport.authorize('twitter', { scope : 'email' }));
// handle the callback after twitter has authorized the user
app.get('/connect/twitter/callback',
passport.authorize('twitter', {
successRedirect : '/admin',
failureRedirect : '/'
}));
// google ---------------------------------
// send to google to do the authentication
app.get('/connect/google', passport.authorize('google', { scope : ['profile', 'email'] }));
// the callback after google has authorized the user
app.get('/connect/google/callback',
passport.authorize('google', {
successRedirect : '/admin',
failureRedirect : '/'
}));
// =============================================================================
// UNLINK ACCOUNTS =============================================================
// =============================================================================
// used to unlink accounts. for social accounts, just remove the token
// for local account, remove email and password
// user account will stay active in case they want to reconnect in the future
// local -----------------------------------
app.get('/unlink/local', isLoggedIn, function(req, res) {
var user = req.user;
user.email = undefined;
user.password = undefined;
user.save(function(err) {
res.redirect('/profile');
});
});
// facebook -------------------------------
app.get('/unlink/facebook', isLoggedIn, function(req, res) {
var user = req.user;
user.facebook.token = undefined;
user.save(function(err) {
res.redirect('/profile');
});
});
// twitter --------------------------------
app.get('/unlink/twitter', isLoggedIn, function(req, res) {
var user = req.user;
user.twitter.token = undefined;
user.save(function(err) {
res.redirect('/profile');
});
});
// google ---------------------------------
app.get('/unlink/google', isLoggedIn, function(req, res) {
var user = req.user;
user.google.token = undefined;
user.save(function(err) {
res.redirect('/profile');
});
});
// route middleware to ensure user is logged in
function isLoggedIn(req, res, next) {
if (req.isAuthenticated())
return next();
res.redirect('/');
}
//=======================================================================================
// socket io checking connection here
//========================================================================================
// var rooms = ['1','2','3','4','5'];
io.on("connection", function(socket){
var defaultroom = 'general';
/* socket.broadcast.to('game').emit('message', 'nice game');
When a new user connects to our server, we expect an event called "newUser"
and then we'll emit an event called "newConnection" with a list of all
participants to all connected clients
*/
// socket.emit('setup',{
// rooms: rooms
// });
socket.on('message',function(data){
console.log(data);
// var newMsg = new Chat({
// username: data.username,
// content: data.message,
// room: data.room,
// created: new Date()
// });
// console.log(newMsg);
// newMsg.save();
console.log("here in socket message"+" "+data.room+" "+data.message);
io.sockets.in(data.room).emit("incomingMessage",{message:data.message});
// socket.broadcast.to(data.room).emit("incomingMessage",{message:data.message});
});
socket.on("newUser", function(data) {
data.room = data.room;
socket.join(data.room);
console.log(data);
participants.push({id: data.id, name: data.name});
io.sockets.emit("newConnection", {participants: participants,room:data.room});
});
// io.in(defaultroom).emit('newConnection',{participants: participants});
/*
When a user changes his name, we are expecting an event called "nameChange"
and then we'll emit an event called "nameChanged" to all participants with
the id and new name of the user who emitted the original message
*/
socket.on("nameChange", function(data) {
_.findWhere(participants, {id: socket.id}).name = data.name;
io.sockets.emit("nameChanged", {id: data.id, name: data.name});
});
/*
When a client disconnects from the server, the event "disconnect" is automatically
captured by the server. It will then emit an event called "userDisconnected" to
all participants with the id of the client that disconnected
*/
socket.on("disconnect", function() {
participants = _.without(participants,_.findWhere(participants, {id: socket.id}));
io.sockets.emit("userDisconnected", {id: socket.id, sender:"system"});
});
//Listens to new chat
// socket.on('new message', function(data) {
//// Create message
// var newMsg = new Chat({
// username: data.username,
// content: data.message,
// room: data.room.toLowerCase(),
// created: new Date()
// });
// //Save it to database
// newMsg.save(function(err, msg){
// //Send message to those connected in the room
// io.in(msg.room).emit('message created', msg);
// });
// });
socket.on('roomChange',function(data){
socket.join(data.room);
console.log(data.room);
io.in(data.room).emit("newConnection",{participants:participants,room:data.room});
});
});
//Start the http server at port and IP defined before
http.listen(app.get("port"), function() {
console.log("Server up and running. Go to http://" + "heyU" + ":" + app.get("port"));
});