-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
534 lines (489 loc) · 19.3 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
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
var express = require('express');
var mongo = require('mongodb').MongoClient;
var session = require('express-session');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var passport = require('passport');
var Strategy = require('passport-local').Strategy;
var md5 = require('md5');
var nodemailer = require('nodemailer');
var emailCheck = require('email-check');
var transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
port: 465,
secure: true, // secure:true for port 465, secure:false for port 587
auth: {
pass: process.env.MAILPW
}
});
var mail_template = require('./views/welcome_mail');
var dburl = process.env.DBURL;
var port = process.env.PORT;
var app = express();
app.use(express.static(`${__dirname}/views`));
app.use(bodyParser.json()); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
app.use(session({
secret: "Shh, its a secret!"
}));
app.set('vew engine', 'ejs');
//PASSPORT FOR AUTHENTICATION
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(null, user);
});
passport.use(new Strategy(
function (username, password, done) {
mongo.connect(dburl, function (err, db) {
if (err) {
console.log(err);
} else {
var col = db.collection('data');
username = username.toLowerCase();
col.find({
username: username
}, {
_id: 0
}).toArray(function (err, ress) {
if (err) {
console.log(err);
} else {
if (ress.length == 0) {
console.log('user not found!');
done(null, false);
} else {
if (md5(password) == ress[0].hash) {
console.log('Verified!');
return done(null, ress[0]);
} else {
console.log('Wrong password!');
done(null, false);
}
}
}
});
}
});
}));
//ROUTES
//HOME PAGE
app.get('/', function (req, res) {
res.render('home.ejs', {});
});
//SIGN UP PAGE
app.get('/signup', function (req, res) {
console.log('\nSIGNUP ROUTE GET');
res.render('signup.ejs');
});
//POSTING SIGNUP DATA
app.post('/signup', function (req, res) {
console.log('\nSIGNUP ROUTE POST');
var username = req.body.username.toLowerCase();
var email = req.body.email;
//PASSWORD IS HASHED WITH MD-5 AND THAT DIGEST IS STORED AT THE DATABASE
var hash = md5(req.body.password);
//VALIDATING EMAIL
emailCheck(email).then(function (stat) {
if (stat) {
mongo.connect(dburl, function (err, db) {
if (err) {
console.log(err);
res.json({
alert: 'Cannot connect to db'
});
} else {
var col = db.collection('data');
col.find({
username: username
}).toArray(function (err, ress) {
if (err) {
console.log(err);
res.json({
alert: 'db err'
});
} else {
if (ress.length > 0) {
console.log('User exists');
res.json({
log: 'Username taken',
code: 101
});
} else {
col.find({
email: email
}).toArray(function (err, results) {
if (err) {
console.log(err);
} else {
if (results.length > 0) {
console.log('email taken');
res.json({
code: 750
});
} else {
var user = {};
user.username = username;
user.hash = hash;
user.email = email;
user.key = `mailerkey${Date.now()}`;
user.projects = [];
col.insert(user);
res.json({
alert: 'Thank you. Log in with your credentials.',
log: user.key,
code: 100,
redirect: '/'
});
console.log('DONE');
////SENDING THE WELCOME MESSAGE
var html = mail_template.mail;
let mailOptions = {
from: 'mailer', // sender address
to: email, // list of receivers
subject: `Welcome to Mailer, ${username}!`, // Subject line
text: 'Welcome to Mailer!', // plain text body
html: html // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('\n\nMessage sent to User');
});
/*SENDING ME A MESSAGE THAT A NEW MEMBER HAS REGISTERED*/
col.find({}).toArray(function (err, all) {
console.log("\n\nNEW ROUTE");
if (err) {
console.log(err);
} else {
var allDocs = all.length;
var mailOptions2 = {
from: 'mailer', // sender address
subject: "New Registraion on Mailer!", // Subject line
text: "New Registraion on Mailer!", // plain text body
html: mail_template.reg + `Time: ${Date()} <br> Email: ${email} <br>Username: ${username}<br><br>Currently Registered Users: ${allDocs}` // html body
};
console.log("\nALL DOCS: " + allDocs);
transporter.sendMail(mailOptions2, (error, info) => {
if (error) {
console.log("\nERROR IN NEW MAIL SENDING");
return console.log(error);
}
console.log("\n\nMAIL SENT!");
console.log('\n\n', info);
});
}
});
}
}
});
}
}
});
}
});
} else {
res.json({
alert: "Invalid email address!",
log: "Invalid email address",
code: 105
});
}
}).catch(function (err) {
console.log(err);
res.json({
alert: "Invalid email address!",
log: "Invalid email address",
code: 105
});
});
});
/*POSTING DATA THROUGH HOME PAGE (LOGIN PAGE)
IF AUTHENTICATION SUCCESS, DIRECTED TO /SUCCESS, OTHERWISE TO /FAIL*/
app.post('/login',
passport.authenticate('local', {
failureRedirect: '/fail'
}),
function (req, res) {
res.redirect('/success');
});
app.get('/success', function (req, res) {
if (req.user) {
res.json({
redirect: '/profile'
});
} else {
res.json({
alert: 'Logged in as GUEST',
redirect: '/fail'
});
}
});
app.get('/fail', function (req, res) {
res.json({
alert: 'Login Failure. Please check username and password.'
});
});
/*SUBMITTING A NEW PROJECT WITH SUBIT BUTTON ON PROFILE PAGE*/
app.post('/submit_project', function (req, res) {
var project = req.body.project;
var id = Date.now();
//IF NOT LOGGED IN ALERT THE USER
if (!req.user) {
res.json({
alert: 'Please log in to submit projects...'
});
} else {
mongo.connect(dburl, function (err, db) {
if (err) {
console.log(err);
res.json({
alert: 'Error connecting to database'
});
} else {
var col = db.collection('data');
col.find({
username: req.user.username
}, {
_id: 0
}).toArray(function (err, ress) {
if (err) {
console.log(err);
res.json({
alert: 'Error connecting to database'
});
} else {
//FINDIN IF A PROJECT WITH THE SAME NAME EXISTS
var exists = false;
ress[0].projects.forEach(function (item) {
if (item.name == project) {
exists = true;
}
});
if (exists) {
res.json({
code: 300
});
db.close();
} else {
var sub = {};
if (req.body.redirect) {
sub.redirect = req.body.redirect;
}
sub.name = project;
sub.id = id;
ress[0].projects.push(sub);
col.update({
username: req.user.username
}, ress[0]);
console.log('DB UPDATED!');
db.close();
res.json({
code: 400,
projects: ress[0].projects
});
}
}
});
}
});
}
});
/*REMOVING A PROJECTS WITH REMOVE BUTTON UNDER MY PROJECTS*/
app.post('/remove', function (req, res) {
if (!req.user) {
res.json({
alert: 'Please log in first'
});
} else {
var name = req.body.name;
mongo.connect(dburl, function (err, db) {
if (err) {
console.log(err);
res.json({
alert: 'Error connecting to database',
log: err
});
} else {
var col = db.collection('data');
col.find({
username: req.user.username
}, {
_id: 0
}).toArray(function (err, ress) {
if (err) {
console.log(err);
res.json({
alert: 'Error connecting to databse',
log: err
});
} else {
var index;
for (var i = 0; i < ress[0].projects.length; i++) {
if (ress[0].projects[i].name == name) {
index = i;
}
}
ress[0].projects.splice(index, 1);
col.update({
username: req.user.username
}, ress[0]);
res.json({
code: 500,
projects: ress[0].projects
});
}
});
}
});
}
});
//LOGGING OUT THE USER
app.get('/logout', function (req, res) {
req.logout();
res.redirect('/');
});
/*SENT THE USER HERE FROM SUCCESS ROUTE AFTER AUTHENTICATION*/
app.get('/profile', function (req, res) {
if (req.user) {
console.log(req.user);
res.render('profile.ejs', req.user);
} else {
console.log('\nNOT LOGGED IN!');
res.render('profile.ejs', {
username: 'GUEST'
});
// res.send('Authentication error! Please log in');
}
});
/*GETTING USER'S PROJECT WITH ANGULAR*/
app.get('/myProjects', function (req, res) {
if (req.user) {
mongo.connect(dburl, function (err, db) {
if (err) {
console.log(err);
res.json({
alert: 'mongo err. See log',
log: err
});
} else {
var col = db.collection('data');
col.find({
username: req.user.username
}, {
_id: 0
}).toArray(function (err, ress) {
if (err) {
console.log(err);
res.json({
alert: 'Mongo err. see log',
log: err
});
} else {
res.json({
log: 'Success at obtainig user projects',
projects: ress[0].projects,
code: 200
});
db.close();
}
});
}
});
} else {
res.json({
alert: 'Not logged in'
});
}
});
/*GETTING FORM DATA*/
app.post('/mailer', function (req, res) {
console.log('\nMAILER ROUTE');
var message = req.body;
console.log(message);
var id = req.query.id;
mongo.connect(dburl, function (err, db) {
if (err) {
console.log(err);
} else {
var col = db.collection('data');
var found = false;
var email, username, project, redirect;
col.find({}).toArray(function (err, ress) {
if (err) {
console.log(err);
} else {
ress.forEach(function (user) {
user.projects.forEach(function (item) {
if (!found) {
if (item.id == id) {
found = true;
email = user.email;
username = user.username;
project = item.name;
if (item.redirect) {
redirect = item.redirect;
} else {
redirect = '/default_redirect';
}
}
}
});
});
if (found) {
var html = '<h2 style=\"text-align:center; margin-top:20px; margin-bottom:20px;\">Form data from ' + project + '</h2>';
for (var key in message) {
html += '<strong>' + key + ': </strong> ' + message[key] + '<br>';
}
html += '<br><div style=\"text-align:center; font-size:15px; margin-top:40px; margin-bottom:20px; padding-top:20px; border-top:1px solid grey;\">generated by <span style=\"color:blue; font-size:20px\">Mailer</span></div>';
console.log(html);
let mailOptions = {
from: 'mailer', // sender address
to: email, // list of receivers
subject: `Form submission from ${project}`, // Subject line
text: 'Data', // plain text body
html: html // html body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
return console.log(error);
}
console.log('Message %s sent: %s', info.messageId, info.response);
});
res.redirect(redirect);
} else {
res.render('broken.ejs');
}
}
});
}
});
});
/*IF DEFAULT REDIRECT WAS SELECTED, THIS THANK YOU PAGE IS DISPLAYED*/
app.get('/default_redirect', function (req, res) {
res.render('default_redirect.ejs');
});
/*HOW TO PAGE*/
app.get('/howto', function (req, res) {
if (req.user) {
res.render('howto.ejs', req.user);
} else {
res.render('howto.ejs', {
username: 'GUEST'
});
}
});
/*STARTING THE SERVER*/
app.listen(port, function () {
console.log(`App started on port ${port}`);
});