-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
587 lines (511 loc) · 17.6 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
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
const express = require('express');
const app = express ();
const path = require('path');
const ejsMate = require('ejs-mate');
const mongoose = require("mongoose");
const passport = require('passport');
const localStrategy = require('passport-local');
const session = require('express-session');
const exphbs = require('express-handlebars');
const messagebird = require('messagebird')('thsMs0oPRrJbNEbwegMHgnFPp');
const flash = require('connect-flash');
const User = require('./models/user');
var nodemailer = require('nodemailer');
var bodyParser = require("body-parser");
const Notice = require("./models/Notices");
const Event = require("./models/Events");
const http = require('http');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {
userJoin,
getCurrentUser,
userLeave,
getRoomUsers
} = require('./utils/users');
const server = http.createServer(app);
const io = socketio(server);
const botName = 'ChatBox';
require('dotenv').config();
mongoose.connect(process.env.MONGODB_URI,{
useNewUrlParser : true,
useCreateIndex: true,
useUnifiedTopology:true,
})
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
app.engine("ejs", ejsMate);
app.set('views', path.join(__dirname, 'views'))
app.use(express.static(__dirname + '/staticfiles'));
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({extended:true}));
app.use(require("express-session")({
secret: "Rusty is the best and cutest dog in the world",
resave:false,
saveUninitialized: false
}))
const sessionConfig = {
secret: 'thisshouldbeabettersecret!',
resave: false,
saveUninitialized: true,
cookie: {
httpOnly: true,
expires: Date.now() + 1000 * 60 * 60 * 24 * 7,
maxAge: 1000 * 60 * 60 * 24 * 7
}
}
mongoose.set('useFindAndModify', false);
app.use(session(sessionConfig));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(express.static(__dirname + '/staticfiles'));
app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.urlencoded({extended:true}));
app.set('view engine', 'ejs');
app.use((req, res, next) => {
res.locals.currentUser = req.user;
if(req.user) {
firstname = req.user.firstname;
collegename= req.user.collegename;
}
res.locals.success = req.flash('success');
res.locals.error = req.flash('error');
next();
})
const isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl
req.flash('error', 'You must be signed in first!');
return res.redirect('/login');
}
next();
}
// Run when client connects
io.on('connection', socket => {
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
// Welcome current user
socket.emit('message', formatMessage(botName, 'Welcome to ChatBox!'));
// Broadcast when a user connects
socket.broadcast
.to(user.room)
.emit(
'message',
formatMessage(botName, `${user.username} has joined the chat`)
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listen for chatMessage
socket.on('chatMessage', msg => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if (user) {
io.to(user.room).emit(
'message',
formatMessage(botName, `${user.username} has left the chat`)
);
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
var PORT = process.env.PORT || 3000;
app.get("/home", isLoggedIn, async (req, res) => {
const member = await User.findById(req.user._id);
if (!member.isstudent) {
req.flash("error", "Bad Request");
return res.redirect('/');
}
var users = await User.find({});
var alumnicount = 0, batchmates = 0, userinlocation = 0;
for (let field of users) {
if (!field.collegename)
alumnicount++;
}
var users = await User.find({'acollegename': req.user.acollegename});
batchmates = users.length;
var users = await User.find({'currentlocation': req.user.currentlocation});
userinlocation = users.length;
var college = await User.find({collegename : req.user.acollegename}).populate('Events').populate('Notices');
res.render('home.ejs', {alumnicount, batchmates, userinlocation, college});
})
app.get("/", async (req, res) => {
if (req.user) {
if (req.user.collegename) {
return res.redirect('/college');
}
else {
return res.redirect('/home');
}
}
var users = await User.find({});
var collegecount = 0, alumnicount = 0;
for (let field of users) {
if (field.collegename)
collegecount++;
else
alumnicount++;
}
var events = await Event.find({}).sort('EventDate').exec(function(err, docs) { });
res.render('landing_page.ejs', {collegecount, alumnicount});
})
app.get("/profile", isLoggedIn, async (req, res) => {
const alumni = await User.findById(req.user._id);
var alumnilogin = false, collegelogin = false, editprofile = true, profile=false;
if (req.user.collegename)
collegelogin = true;
else
alumnilogin=true;
res.render('profile', {alumni, collegelogin, alumnilogin, editprofile, profile});
})
app.get('/verifyprofile/:id', isLoggedIn, async (req, res) => {
const { id } = req.params;
const alumni = await User.findById(id);
var alumnilogin = false, profile = true, collegelogin = false, editprofile = false;
alumnilogin=true;
res.render('profile', {alumni, collegelogin, alumnilogin, profile, editprofile});
})
app.get('/verifyaccount/:id', isLoggedIn, async (req, res) => {
var transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.EMAIL_ID,
pass: process.env.EMAIL_PASS
}
});
var alumni = await User.findById(req.params.id);
var mailOptions = {
from: process.env.EMAIL_ID,
to: alumni.email,
subject: 'Regarding Account Verification',
text: `\nCongratulations Your account was verified as alumnus of ${req.user.collegename}.\nNow you can enjoy full range of services on the Portal.\n\nRegards,${req.user.collegename}\n${req.user.clocation}\n`
};
await transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
const { id } = req.params;
await User.findOneAndUpdate({"_id":id}, { "verified": true} );
return res.redirect('/college');
})
app.get('/alumniprofile/:id', isLoggedIn, async (req, res) => {
const { id } = req.params;
const alumni = await User.findById(id);
var profile = false, collegelogin = false, alumnilogin=true, editprofile=false;
res.render('profile', {alumni, collegelogin, alumnilogin, profile, editprofile});
})
app.get("/college", isLoggedIn, async (req, res) => {
const member = await User.findById(req.user._id);
if (member.isstudent) {
req.flash("error", "Bad Request");
backURL=req.header('Referer') || '/';
return res.redirect(backURL);
}
if(req.user) {
const college = await User.findById(req.user._id).populate('Events').populate('Notices');
const allusers = await User.find({"acollegename":req.user.collegename});
var verified = [], notverified = [];
for (let alumni in allusers) {
if (allusers[alumni].isstudent) {
if (allusers[alumni].verified) {
verified.push(allusers[alumni]);
}
else {
notverified.push(allusers[alumni]);
}
}
}
res.render('college.ejs', {College : college, verified, notverified});
}
else {
console.log("no id");
}
})
app.get("/editprofile", isLoggedIn, async (req, res) => {
const alumni = await User.findById(req.user._id);
var alumnilogin = false, collegelogin = false;
if (req.user.collegename)
collegelogin = true;
else
alumnilogin=true;
res.render('editprofile.ejs', {alumni, collegelogin, alumnilogin});
})
app.post('/editprofile', isLoggedIn, async (req, res) => {
if (!req.body.password.length) {
delete req.body.password;
}
else {
req.user.setPassword(req.body.password, function() {
req.user.save();
})
}
var alumni = await User.findOneAndUpdate({"_id":req.user._id}, req.body);
alumni = await User.findOne({"_id":req.user._id});
req.flash("success", "Profile edited Successfully");
return res.redirect("/profile");
})
app.get('/deleteaccount', isLoggedIn, async (req, res) => {
if (req.user.collegename) {
const colleges = await User.deleteMany({"acollegename":req.user.collegename});
const user = await User.findOneAndDelete({"_id": req.user._id});
}
else {
const user = await User.findOneAndDelete({"_id": req.user._id});
}
req.flash('success', 'Account Deleted');
return res.redirect("/");
})
app.get('/invaliduser/:id', isLoggedIn, async (req, res) => {
const {id} = req.params;
await User.deleteOne({"_id": id});
return res.redirect("/college");
})
app.get("/login", (req, res) => {
if (req.user) {
if (req.user.collegename)
return res.redirect('/college');
else
return res.redirect('/home')
}
res.render('login');
})
app.get('/alumniregister', async (req, res) => {
if (req.user) {
if (req.user.collegename)
return res.redirect('/college');
else
return res.redirect('/home')
}
var users = await User.find({});
var allusers = [];
for (let college of users) {
if (college.collegename)
allusers.push(college);
}
res.render('alumniregister.ejs', {allusers});
})
app.get('/collegeregister', (req, res) => {
if (req.user) {
if (req.user.collegename)
return res.redirect('/college');
else
return res.redirect('/home')
}
res.render('collegeregister');
})
app.get("/contact-us", (req, res) => {
res.render('contact-us.ejs');
})
app.get("/about-us", (req, res) => {
res.render('about-us.ejs');
})
app.post("/collegeNotice", isLoggedIn, async (req,res) => {
if(req.user) {
// console.log(req.body)
const college = await User.findById(req.user._id);
const notice = new Notice(req.body)
college.Notices.push(notice);
await notice.save();
await college.save();
res.redirect("/college");
}
else {
console.log("no id")
}
})
app.get("/deletenotice/:id", isLoggedIn, async (req,res) => {
const { id } = req.params;
await User.findByIdAndUpdate(req.user._id, { $pull: { Events: id } });
await Notice.findByIdAndDelete(id);
return res.redirect('/college');
})
app.get("/deleteevent/:id", isLoggedIn, async (req,res) => {
const { id } = req.params;
await User.findByIdAndUpdate(req.user._id, { $pull: { Notices: id } });
await Event.findByIdAndDelete(id);
return res.redirect('/college');
})
app.post("/collegeEvent", async (req,res) => {
if(req.user) {
// console.log(req.body)
const college = await User.findById(req.user._id);
const event = new Event(req.body)
college.Events.push(event);
await event.save();
await college.save();
res.redirect("/college");
}
else {
console.log("no id")
}
})
app.post('/login', passport.authenticate('local', { failureFlash: true, failureRedirect: 'login' }), async (req, res) => {
console.log(req.body)
var df = '';
const user = await User.find({'username' : req.body.username},'name skill', function(err,docs){
if (err) {
req.flash('error', err.message);
console.log('error occured in the database');
}
df = docs;
});
console.log('df ' + df)
temp = await User.findById(df).exec();
if (temp.isstudent) {
req.flash('success', 'welcome back!');
return res.redirect('/home');
}
else {
req.flash('success', 'welcome back!');
return res.redirect('/college');
}
console.log(temp);
console.log(temp.ccontact);
//console.log(temp.password);
})
app.post("/register", async (req, res) => {
var { collegename } = req.body;
if (collegename) {
var {collegeemail, cpass1, cpass2, ccontact, clocation, cpass1, cpass2} = req.body;
var username = collegeemail;
var password = cpass1;
var isstudent = false;
const user = new User({ collegeemail, collegename, ccontact, clocation, username, isstudent });
const registeredUser = await User.register(user, password,
function(err, user) {
if (err) {
req.flash('error', err.message);
return res.redirect("/collegeregister");
}
req.flash('success', "Successfully Registered!!!!");
return res.redirect("/login");
});
}
else {
var {firstname, lastname, currentworking, email, contact, currentlocation, acollegename, yearofpassing, degree, branch, pass1, pass2, gender} = req.body;
var username = email;
var password = pass1;
var verified = false;
var isstudent = true;
const user = new User({ firstname, lastname, currentworking, email, contact, currentlocation, acollegename, yearofpassing, degree, branch, username, verified, isstudent, gender });
const registeredUser = await User.register(user, password,
function(err, user) {
if (err) {
req.flash('error', err.message);
return res.redirect("/alumniregister");
}
req.flash('success', "Successfully Registered!!!!");
return res.redirect("/login");
});
}
})
app.get('/logout', (req, res) => {
req.logout();
req.flash('success', "Goodbye!");
res.redirect('/');
})
app.post('/sendmessage/:id', async (req, res) => {
var transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.EMAIL_ID,
pass: process.env.EMAIL_PASS
}
});
var mailOptions = {
from: process.env.EMAIL_ID,
to: '[email protected]',
subject: 'Query regarding alumniportal',
text: `From - ${req.body.name}\nEmail - ${req.body.email}\n${req.body.message}`
};
await transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.redirect('/home');
})
app.get("/sendmail/:id",isLoggedIn, async (req, res) => {
res.render('sendmail', {'id':req.params.id});
})
app.post('/sendmail/:id', async (req, res) => {
console.log(process.env)
console.log(req.body)
var transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT,
secure: false,
auth: {
user: process.env.EMAIL_ID,
pass: process.env.EMAIL_PASS
}
});
var alumni = await User.findById(req.params.id);
var mailOptions = {
from: process.env.EMAIL_ID,
to: alumni.email,
subject: req.body.subject,
text: req.body.mailbody
};
await transporter.sendMail(mailOptions, function(error, info){
if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
});
res.redirect('/searchalumni');
})
app.get('/searchalumni', isLoggedIn, async (req, res) => {
if (!req.user.collegename)
return res.redirect('/home');
const alumni = await User.find({"acollegename" : req.user.collegename, "verified" : true});
res.render('searchalumni', {alumni});
})
app.post('/searchalumni', isLoggedIn, async (req, res) => {
if (req.body.yearofpassing == 'Passing Year')
delete req.body.yearofpassing;
if (req.body.degree == 'Degree')
delete req.body.degree;
if (req.body.branch == 'Branch')
delete req.body.branch;
req.body.acollegename = req.user.collegename;
req.body.verified = true;
const alumni = await User.find(req.body);
res.render('searchalumni', {alumni});
})
app.get("/chat", isLoggedIn,(req,res) => {
res.render("index.ejs");
})
app.get("/chatroom", isLoggedIn, (req,res) => {
res.render("chat.ejs", {user :req.body.username, room : req.body.collegename})
})
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));