-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
1284 lines (1171 loc) · 43.1 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
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express');
const nodemailer = require("nodemailer");
const app = express();
const auth = require('./auth');
const commentDB = require('./public/projectPage/comments.js')
const dbconnect = require('./db_connect');
const path = require("path");
const multer = require('multer');
const exphbs = require('express-handlebars');
let Client = require('ssh2-sftp-client');
let sftp = new Client();
//SSL
const https = require('https');
const fs = require('fs');
var sslOptions = {
key: fs.readFileSync('./key.pem'),
cert: fs.readFileSync('./cert.pem')
}
var bodyParser = require('body-parser');
var session = require('express-session');
var sftpStorage = require('multer-sftp-linux');
// objects for multer storage configurations
var storage;
//This is for parsing json POST requests in text
// create application/json parser
var jsonParser = bodyParser.json();
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false });
// setting multer storage configuration based on whether it is on vm or localhost
if (process.env.HOSTNAME === 'studentworks') {
storage = multer.diskStorage({
destination: "public/userPhotos",
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
}
});
} else {
storage = sftpStorage({
sftp: {
host: 'myvmlab.senecacollege.ca',
port: 6185,
username: 'stephen',
password: 'sux'
},
destination: function (req, file, cb) {
cb(null, path.posix.join('./StudentWorks', 'public', 'userPhotos'));
},
filename: function (req, file, cb) {
cb(null, path.basename(file.originalname, path.extname(file.originalname)) + '-' + Date.now() + path.posix.extname(file.originalname));
}
});
}
var mediaForProject = multer.diskStorage({
destination: "project/temp",
filename: function (req, file, cb) {
cb(null, path.basename(file.originalname, path.extname(file.originalname)) + '-' + Date.now() + path.extname(file.originalname));
}
});
var upload = multer({ storage: storage });
var uploadContribute = multer({ storage: mediaForProject });
var uploadVideo = multer({ storage: mediaForProject });
/*
Here we are configuring our SMTP Server details.
STMP is mail server which is responsible for sending and recieving email.
*/
var smtpTransport = nodemailer.createTransport({
service: "Gmail",
auth: {
user: "studentworks10",
pass: "prj666_182a07"
}
});
/*------------------SMTP Over-----------------------------*/
//File usage
//app.use(auth); // For authenticating, please do not comment out until the project is done.
app.use(express.static('public'));
app.use(express.static('project'));
app.use(session({
secret: "keyboard warriors",
name: "session",
resave: true,
saveUninitialized: false,
cookie: { maxAge: 600000 } //cookies expire in 10 minutes
})); // used to generate session tokens
app.engine('.hbs', exphbs({ extname: '.hbs' })); // tells server that hbs file extensions will be processed using handlebars engine
app.set('view engine', '.hbs');
/*------------------Routing Started ------------------------*/
/* Sets header to not cache the pages
This disables the behaviour where user has access to restricted pages after logout
MUST be applied before the other routes*/
app.use(function (req, res, next) {
if (!req.user)
res.header('Cache-Control', 'private, no-cache, no-store, must-revalidate');
next();
});
//function call to make sure user is logged in ** USED for recording page**.
function ensureLogin(req, res, next) {
if (!req.session.authenticate) {
res.redirect("/login");
} else {
next();
}
};
// VIDEO RECORDING UPLOAD page
app.post("/upload-recording", uploadContribute.fields([{ name: "image", maxCount: 1 }]), (req, res) => {
// FRONT-END guarantees that all values are present, escept 'category' which is optional;
// Project image and video is in /project/temp folder and of proper format
// flags for validating fields
var validateResult = true;
var validateLength = true;
//checks for the required text fields in req.body
function checkTextFieldExist(key) {
if (req.body[key] === undefined || req.body[key] == "") {
//console.log ("req.body key:", req.body[key], key);
validateResult = false;
res.status(400).send("validation error");
}
// ensure userID is a number greater than 0
if (key == 'userID') {
if (isNaN(req.body[key]) || req.body[key] < 0) {
validateResult = false;
res.status(400).send("validation error");
}
}
}
// creates a project object that stores all the validated fields
console.log(req.body);
var project = {
userID: req.body.userID,
title: req.body.title,
language: req.body.language,
framework: req.body.framework,
platform: req.body.platform,
category: (req.body.category === undefined) ? "" : req.body.category,
desc: req.body.desc,
color: req.body.color,
imageFilePath: `temp/${req.files['image'][0].filename}`,
videoFilePath: req.body.videoUpload
}
//console.log ("project object", project);
// Updating DB with the data in project object
var result;
async function addProjectInDB(project) {
dbconnect.connect();
let promise = new Promise((resolve, reject) => {
dbconnect.createProjectFromContribute(project, function (err, data) {
if (err) {
reject(err);
throw err;
} else {
// returns the projectID of the newly created project
resolve(data.insertId);
}
});
});
// waits and captures the projectId
result = await promise;
dbconnect.end();
return new Promise(function (resolve, reject) {
// console.log ("projectId:", result);
// Note: can only return one object back to next function, which is result
resolve(result);
});
}
function assocociateUserToProjectInDB(projectId) {
dbconnect.connect();
dbconnect.associateUserToProject(project, projectId, (err, data) => {
if (err) {
throw err;
}
});
dbconnect.end();
}
addProjectInDB(project)
.then(assocociateUserToProjectInDB, null)
.catch(function (rejectMsg) {
// stuff
});
res.status(200).send('success');
});
// PROJECT UPLOAD page
app.post("/upload-project", uploadContribute.fields([{ name: "image", maxCount: 1 }, { name: "video", maxCount: 1 }]), (req, res) => {
// FRONT-END guarantees that all values are present, escept 'category' which is optional;
// Project image and video is in /project/temp folder and of proper format
// flags for validating fields
var validateResult = true;
var validateLength = true;
//checks for the required text fields in req.body
function checkTextFieldExist(key) {
if (req.body[key] === undefined || req.body[key] == "") {
//console.log ("req.body key:", req.body[key], key);
validateResult = false;
res.status(400).send("validation error");
}
// ensure userID is a number greater than 0
if (key == 'userID') {
if (isNaN(req.body[key]) || req.body[key] < 0) {
validateResult = false;
res.status(400).send("validation error");
}
}
}
// checks against the length of each input field against their max field lengths
function checkFieldLength(value, key) {
if (req.body[key]) {
if (req.body[key].length > value) {
validateLength = false;
res.status(400).send("validation error - field length");
}
}
if (req.files[key] != undefined) {
if (req.files[key][0].path.length > value) {
validateLength = false;
res.status(400).send("validation error - file path length");
}
}
}
//checks for the required fields in req.files
function checkFilesFieldExist(key) {
if (req.files[key] === undefined || req.files[key] == "") {
validateResult = false;
res.status(400).send("validation error - file");
}
}
// Server side validation - text fields
// note that category field is not required
var reqTextFields = ['userID', 'title', 'language', 'framework', 'platform', 'desc'];
reqTextFields.forEach(checkTextFieldExist);
// Server side validation - files fields
var reqFilesFields = ['image', 'video'];
reqFilesFields.forEach(checkFilesFieldExist);
// maps input field to their max length, and then checks against it
new Map([['title', 30],
['language', 30],
['framework', 30],
['category', 20],
['image', 255],
['video', 255],
]).forEach(checkFieldLength);
// exits function if validation has failed
if (validateResult !== true || validateLength !== true) {
return false;
}
//since multer-sftp does not work for multiple files, we are manually sftping the two files onto vm
if (process.env.HOSTNAME !== 'studentworks') {
sftp.connect({
host: 'myvmlab.senecacollege.ca',
port: 6185,
username: 'student',
privateKey: require('fs').readFileSync('public/publicKey.txt')
//password: process.env.vmpassword
}).then(() => {
sftp.put(req.files['image'][0].path, path.posix.join('./StudentWorks', 'project', 'temp', req.files['image'][0].filename));
sftp.put(req.files['video'][0].path, path.posix.join('./StudentWorks', 'project', 'temp', req.files['video'][0].filename));
}).catch((err) => {
console.log(err, 'Contribute: sftp error');
})
}
// creates a project object that stores all the validated fields
var project = {
userID: req.body.userID,
title: req.body.title,
language: req.body.language,
framework: req.body.framework,
platform: req.body.platform,
category: (req.body.category === undefined) ? "" : req.body.category,
desc: req.body.desc,
color: req.body.color,
imageFilePath: `temp/${req.files['image'][0].filename}`,
videoFilePath: `temp/${req.files['video'][0].filename}`
}
//console.log ("project object", project);
// Updating DB with the data in project object
var result;
async function addProjectInDB(project) {
dbconnect.connect();
let promise = new Promise((resolve, reject) => {
dbconnect.createProjectFromContribute(project, function (err, data) {
if (err) {
reject(err);
throw err;
} else {
// returns the projectID of the newly created project
resolve(data.insertId);
}
});
});
// waits and captures the projectId
result = await promise;
dbconnect.end();
return new Promise(function (resolve, reject) {
// console.log ("projectId:", result);
// Note: can only return one object back to next function, which is result
resolve(result);
});
}
function assocociateUserToProjectInDB(projectId) {
dbconnect.connect();
dbconnect.associateUserToProject(project, projectId, (err, data) => {
if (err) {
throw err;
}
});
dbconnect.end();
}
addProjectInDB(project)
.then(assocociateUserToProjectInDB, null)
.catch(function (rejectMsg) {
// stuff
});
res.status(200).send('success');
});
//MAIN Page
app.get("/", (req, res) => {
res.status(200).render('main', {
authenticate: req.session.authenticate,
userID: req.session.userID,
userType: req.session.userType
});
});
//PROJECT page
app.get('/projectPage', urlencodedParser, (req, res) => {
commentDB.initialize(req.query.id)
.then(commentDB.getAllComments, null)
.then((commentsFromDB)=>{
res.status(200).render('project', {
authenticate: req.session.authenticate,
userID: req.session.userID,
userType: req.session.userType,
comments: commentsFromDB
});
})
.catch((error)=>{
console.log("inside of NO DB CONNECTION");
//don't give em comments if the DB doesn't connect.
res.status(200).render('project', {
authenticate: req.session.authenticate,
userID: req.session.userID,
userType: req.session.userType
});
})
});
//ADDING COMMENTS TO PROJECT PAGE
app.post('/addComment', urlencodedParser, (req, res) =>{
var comment = {
projectID: req.body.projectID,
authorName: req.session.userName ? req.session.userName : "Anonymous",
commentText: req.body.commentText
}
commentDB.addComment(comment).then(() => {
//res.redirect("/");
res.redirect(req.get('referer'));
})
.catch((err) => {
console.log(err);
res.redirect(req.get('referer'));
});
});
app.post('/addReply', urlencodedParser, (req, res) =>{
var comment = {
projectID: req.body.projectID,
authorName: req.session.userName ? req.session.userName : "Anonymous",
commentText: req.body.commentText
}
console.log(comment);
commentDB.addReply(comment).then(() => {
res.redirect(req.get('referer'));
})
.catch((err) => {
console.log(err);
res.redirect(req.get('referer'));
});
});
//PROFILE page
app.get('/profile', (req, res) => {
if (req.session.authenticate) {
res.status(200).render('profile', {
authenticate: req.session.authenticate,
userID: req.session.userID,
userType: req.session.userType
});
} else {
res.status(200).redirect("/login");
}
});
app.get('/profile/:userName', (req, res) => {
function getUser() {
return new Promise(function (resolve, reject) {
dbconnect.connect();
var user = dbconnect.getOneUser(req.params.userName, function (err, data) {
if (err) {
console.log(err); throw err;
} else {
//validate the data here!!
var userInfo = JSON.parse(JSON.stringify(data));
resolve(userInfo);
}
dbconnect.end();
});
});
}
getUser()
.then((data)=>{
console.log(data[0]);
res.render('userProfile', { userInfo: data[0] });
})
.catch((err) => {
res.send("No profile available");
})
});
//PROJECT UPLOAD page
app.get('/contribute', (req,res) => {
var filePath = req.query.video;
//Get rid of project, because it is redundant since app.use(project) already looks in the directory.
if (req.query.video){
filePath = filePath.replace('/project/','');
}
console.log(filePath);
if (req.session.authenticate){
res.status(200).render('contribute', { authenticate : req.session.authenticate,
userID : req.session.userID,
userType : req.session.userType,
videoFile : filePath});
} else {
res.status(200).redirect("/login");
}
});
//RECORDING page + Upload Video
app.get('/recording', ensureLogin, (req,res) => {
res.sendFile(path.join(__dirname, 'public/recording/recording.html'));
});
app.post('/upload-video', uploadVideo.single('video-blob'), (req, res, next) => {
var file = req.file.path;
//turn video path into readable path on VM
var changed = file.replace(/\\/g, '/');
//send back the video path
changed = "/" + changed;
//wiat one second delay to process the video upload
setTimeout(function() {
res.status(200).send(changed);
}, 1000);
});
//ADMINISTRATION page
app.get('/adminPage', (req, res) => {
res.status(200).render('admin', {
authenticate: req.session.authenticate,
userID: req.session.userID,
userType: req.session.userType
});
});
//LOGGER
app.get('/logger/:log', (req, res) => {
if (req.params.log != "") {
let log = "./logger '" + req.params.log + "'";
const { exec } = require('child_process');
exec(log, (err, stdout, stderr) => {
if (err) {
res.send(stderr);
} else {
res.send(stdout);
}
});
} else {
console.log("empty string was passed");
}
});
//Registration page
app.get('/register', function (req, res) {
if (req.session.msg) {
res.render('register', { serverMsg: req.session.msg });
req.session.msg = "";
} else {
res.render('register', { serverMsg: req.session.msg });
}
});
app.get('/complete', function (req, res) {
res.sendFile(path.join(__dirname, 'public/registration/complete.html'));
});
//login page
app.get('/login', function (req, res) {
if (req.session.msg) {
res.render('login', { serverMsg: req.session.msg });
req.session.msg = ""; // resets the msg after sending it to client
} else {
res.render('login');
}
});
//this is for handling the POST data from login webform
app.post('/login', urlencodedParser, function (req, res) {
dbconnect.connect();
if (!req.body) {
return res.sendStatus(400);
}
var username = req.body.username1;
var password = req.body.pass;
//console.log(username, password);
if (!username || !password) {
// Render 'missing credentials'
req.session.msg = "Missing credentials.";
return res.status(401).redirect('/login');
}
var results = dbconnect.getOneUser(username, function (err, data) {
if (err) {
console.log(err); throw err;
} else {
//validate the data here!!
var jsonResult = JSON.parse(JSON.stringify(data));
if (jsonResult.length < 1) {
//case of username not found
req.session.msg = "Invalid Username/Password. Login Failed.";
res.status(401).redirect('/login');
} else {
if (jsonResult[0].password === req.body.pass && jsonResult[0].registrationStatus == true) {
//set your session information here
req.session.authenticate = true;
req.session.userName = username;
req.session.userID = jsonResult[0].userID;
req.session.userType = jsonResult[0].userType;
//redirect back to main page
res.status(200).redirect('/');
} else {
if (jsonResult[0].registrationStatus == false) {
req.session.msg = "Login failed, please verify your email.";
} else {
req.session.msg = "Invalid Username/Password. Login Failed.";
}
res.status(401).redirect('/login');
}
}
}
});
dbconnect.end();
});
/* Email verification start*/
var rand, mailOptions, host, link;
app.post('/send', urlencodedParser, function (req, res) {
if (!req.body) {
return res.sendStatus(400).redirect('/register');
}
if (!req.body.name || !req.body.password1 || !req.body.email) {
req.session.msg = "Missing credentials.";
return res.status(401).redirect('/register');
}
//check if user is already created within the database
var userExist = false;
function getUserExistence() {
dbconnect.connect();
dbconnect.getUserExist(req.body.name, function (err, data) {
if (err) { throw err; }
else {
userExist = data[0].userExist;
}
});
dbconnect.end();
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (userExist === 0) {
resolve(userExist);
} else {
reject(`Username "${req.body.name}" is already taken by another user. Please try again.`);
}
}, 1000);
})
}
function sendMail() {
rand = Math.floor((Math.random() * 100000) + 54);
host = req.get('host');
link = "https://" + req.get('host') + "/verify?id=" + rand + "&name=" + req.body.name;;
mailOptions = {
to: req.body.email,
subject: "Please confirm your Email account",
html: `Hello ${req.body.name},<br>
Please Click on the link to verify your email.<br>
<a href="${link}">Click here to verify</a>
<input type="hidden" value=${req.body.name} name="userName"/>`
}
smtpTransport.sendMail(mailOptions, function (error, response) {
console.log('got into /sendMail');
if (error) {
console.log(error);
res.end("error");
} else {
req.session.msg = "Please check your email for a verification link.";
return res.status(401).redirect('/register');
}
});
return new Promise(function (resolve, reject) {
resolve('sendMail resolved');
})
}
/* this will create a new user into the database based on the 3 fields supplied in login webform
The user created user will be initially be a contriubtor, without a firstName, lastName or affiliated program
The registrationCode will be the random value created when the email was sent
*/
function addUsertoDb() {
dbconnect.connect();
var user = {
firstName: 'NULL',
lastName: 'NULL',
email: req.body.email,
password: req.body.password1,
username: req.body.name,
userType: 'Contributor',
program: 'NULL',
registrationStatus: 'FALSE',
registrationCode: rand
};
var errorMsg = "";
try {
dbconnect.createUser(user);
} catch (err) {
errorMsg = err.message;
}
dbconnect.end();
return new Promise(function (resolve, reject) {
if (errorMsg !== "") {
reject(errorMsg);
} else {
resolve('addUserDb() resolved');
}
})
}
//executing checking user existence, send mail, adding new user to database in synchronous order
getUserExistence()
.then(sendMail, null)
.then(addUsertoDb, null)
.catch(function (rejectMsg) {
//console.log('rejectMsg: ', rejectMsg);
req.session.msg = rejectMsg;
res.status(401).redirect('/register');
});
});
app.get('/verify', function (req, res) {
console.log(req.protocol + "://" + req.get('host'));
var regCodeExist = false;
function getRegCodeExistence() {
dbconnect.connect();
dbconnect.getRegCodeExist(req.query.id, function (err, data) {
if (err) {
throw err;
} else {
//console.log("regCode:", data[0].regCodeExist)
regCodeExist = data[0].regCodeExist;
}
})
dbconnect.end();
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (regCodeExist == 1) {
//console.log('resolved at getRegCodeExisitence');
resolve(req.query.id, regCodeExist);
} else {
reject(`regCode ${req.query.id} was not found in database`);
}
}, 1000);
});
}
function validateRegistration(regCode, regCodeExist) {
//console.log("inside validate registration");
//Update emailRegistration status in database
dbconnect.connect();
dbconnect.validateRegistration(regCode);
dbconnect.end();
req.session.msg = "Email successfully verified.";
res.status(200).redirect('/login');
return new Promise(function (resolve, reject) {
setTimeout(function () {
resolve("Email successfully verified");
}, 1000);
});
}
//if((req.protocol+"://"+req.get('host'))==("http://"+host)) {
if (req.query.id) {
console.log("Domain is matched. Information is from Authentic email");
getRegCodeExistence()
.then(validateRegistration, null)
.catch(function (rejectMsg) {
console.log("email is not verified");
console.log(rejectMsg);
res.end(`<h1>Bad Request</h1>`);
});
} else {
//console.log("from bad request:", req.protocol+"://"+req.get('host'));
//console.log("from bad request:","http://"+host);
res.send("<h1>Request is from unknown source</h1>");
}
}); //email verification end
//Forgot password
app.get("/login/forgotpass", (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'public/login/forgot.html'));
});
app.post("/login/forgotpassword", urlencodedParser, (req, res) => {
var tempPass = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 12);
var userExist = false;
function getUserExistence() {
dbconnect.connect();
dbconnect.getUserExist(req.body.username1, function (err, data) {
if (err) { throw err; }
else {
console.log(data[0].userExist);
userExist = data[0].userExist;
}
});
dbconnect.end();
return new Promise(function (resolve, reject) {
setTimeout(function () {
if (userExist === 0) {
reject(`Username "${req.body.username1}" is not in our system!`);
} else {
resolve(userExist);
}
}, 1000);
})
}
function getUser() {
return new Promise(function (resolve, reject) {
dbconnect.connect();
dbconnect.getOneUser(req.body.username1, function (err, data) {
if (err) {
//need to update the page to say no user is found
reject();
}
//we have a user, go at it...
else {
//grab user data
var user = JSON.parse(JSON.stringify(data));
//send an e-mail for user to access new password.
var passlink = "https://myvmlab.senecacollege.ca:6193/forgotpass/complete";
var newMailOptions = {
to: user[0].email,
subject: "StudentWorks Password Recovery",
html: `Hello ${user[0].userName} ,<br> A request has been made to change your password. <br> Your temporary password is: ` + tempPass + ` <br><a href=` + passlink + `>Click here to change your password</a>`
}
smtpTransport.sendMail(newMailOptions, function (error, response) {
console.log('got into /sendMail');
if (error) {
console.log(error);
res.end("error");
reject();
} else {
res.status(200).redirect('/check-email');
resolve();
}
});
}
});
});
dbconnect.end();
}
function updatePassword() {
return new Promise(function (resolve, reject) {
dbconnect.connect();
dbconnect.updatePasswordByUsername(req.body.username1, tempPass, function (err, data) {
if (err) {
console.log("could not update password");
reject();
}
else {
resolve();
}
});
dbconnect.end();
});
};
getUserExistence()
.then(getUser, null)
.then(updatePassword, null)
.catch(function (rejectMsg) {
console.log('rejectMsg: ', rejectMsg);
req.session.msg = rejectMsg;
res.status(401).redirect('/login');
});
});
app.get("/check-email", (req, res) => {
res.render('email');
});
app.get("/forgotpass/complete", (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'public/registration/complete.html'));
});
//Finish the password resetting (can be used apart from 'Forgetting a password')
app.post('/complete', urlencodedParser, function (req, res) {
console.log('got to /complete');
dbconnect.connect();
var password;
function checkUser() {
return new Promise(function (resolve, reject) {
dbconnect.connect();
dbconnect.getOneUser(req.body.username, function (err, data) {
if (err) {
console.log(err); throw err;
} else {
//validate the data here!!
var jsonResult = JSON.parse(JSON.stringify(data));
if (jsonResult.length < 1) {
//case of username not found
req.session.msg = "Invalid Username/Password. Failed to update password.";
res.status(401).redirect('/login');
} else {
if (jsonResult[0].password === req.body.oldpassword && jsonResult[0].registrationStatus == true) {
resolve("passwords match!");
} else {
if (jsonResult[0].registrationStatus == false) {
req.session.msg = "Password entry failed, please verify your email.";
} else {
req.session.msg = "Invalid Username/Password.Failed to update password.";
}
res.status(401).redirect('/login');
reject();
}
}
}
});
});
}
function getUser() {
return new Promise(function (resolve, reject) {
dbconnect.getOneUser(req.body.username, function (err, data) {
if (err) {
console.log(err); throw err;
} else {
//validate the data here!!
var user = JSON.parse(JSON.stringify(data));
if (user.length < 1) {
//case of username not found
req.session.msg = "Invalid Username/Password. Login Failed.";
res.status(401).redirect('/login');
} else {
if (user[0].password === req.body.oldpassword && user[0].registrationStatus == true) {
//Set user password to new password
var password = req.body.password1;
resolve();
}
else {
req.session.msg = "Passwords did not match.";
reject("Password did not match.");
}
}
}
dbconnect.end();
});
});
};
function updatePassord() {
return new Promise(function (resolve, reject) {
dbconnect.connect();
dbconnect.updatePasswordByUsername(req.body.username, req.body.password1, function (err, data) {
if (err) {
console.log("could not update password");
reject();
}
else {
req.session.authenticate = true;
resolve(res.redirect('/'));
}
});
dbconnect.end();
});
};
checkUser()
.then(getUser, null)
.then(updatePassord, null)
.catch(function (rejectMsg) {
console.log('rejectMsg: ', rejectMsg);
req.session.msg = rejectMsg;
res.status(401).redirect('/register');
});
});
app.post('/profile', upload.single("img-input"), function (req, res) {
//console.log('got to profile');
if (!req.body) {
return res.sendStatus(400).redirect('/profile');
}
const formData = req.body;
const formFile = req.file;
//console.log ("server.js => formFile", JSON.stringify(req.file));
//console.log ("description:", req.body.description);
var user = {
userName: req.body.username,
firstName: req.body.fname,
lastName: req.body.lname,
email: req.body.email,
program: req.body.program,
description: req.body.description,
imagePath: (req.file == null) ? null : `/userPhotos/${req.file.filename}`
}
dbconnect.connect();
dbconnect.updateUserProfile(user, function (err, data) {
if (err) {
res.send(err);
throw err;
} else {
// console.log ("inside updateUserProfile:", user);
// tells the ajax that request was successful
res.send("success");
}
});
dbconnect.end();
})
/*------------------Routing End ------------------------*/
/* Returns information about all users in database */
app.get('/api/getAllUsers', function (req, res) {
dbconnect.connect();
var results = dbconnect.getAllUsers(function (err, data) {
if (err) {
console.log("ERROR: ", err);
} else {
res.writeHead(200, { "Content-type": "application/json" });
res.end(JSON.stringify(data));
}
});
dbconnect.end();
});
app.get('/api/getUserByID/id/:id', function (req, res) {
var userID = req.params.id;
if (req.params.id && !isNaN(req.params.id)) {
dbconnect.connect();