forked from shubhangis91/P565F19P12
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackEnd.js
2001 lines (1782 loc) · 84.2 KB
/
backEnd.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
var mysql = require('mysql');
var express = require('express');
var nodemailer = require('nodemailer');
var bodyParser = require('body-parser');
var path = require('path');
var dateFormat = require('dateformat');
const Chatkit = require('@pusher/chatkit-server');
const chatkit = new Chatkit.default({
instanceLocator: 'v1:us1:37bc05a7-986f-45ba-ab7e-8ad47510f2f2',
key: '57961704-54db-4473-9ec3-97f14f13fbea:k1hpe0uC7RnY/RDd8hxAF6loRSVPjE3+aLn3W7rniEg=',
})
const dotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626
const port = process.env.PORT || 3500;
const pool = mysql.createPool({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password : process.env.DB_PASS,
port: process.env.DB_PORT,
database: process.env.DB,
multipleStatements: true,
connectionLimit: 100,
queueLimit: 50
});
let transporter = nodemailer.createTransport({
service: process.env.MAIL_SERV,
auth: {
user: process.env.MAIL_USER,
pass: process.env.MAIL_PASS
}
});
var skillAssessJson = require(path.join(__dirname, "skillAssessment.json"));
var app = express();
var jobsnuEmail = 'jobsnu.se@gmail.com';
var verificationEmailSubject = 'JOBSNU - E-mail Verification';
var otpEmailSubject = 'JOBSNU - One-Time Password (OTP) for Login';
var applicationEmailJsSubject = 'JOBSNU - Job Application Submitted';
var applicationEmailRecSubject = "JOBSNU - New Application Received";
let passwordResetSubject = "JOBSNU - Password Updated Successfully";
app.use(express.static(path.join(__dirname, "jobsnu", "build")));
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
// HELPER FUNCTIONS
function calculateWorkEx(noOfMonths)
{
let workExNoOfYears = parseInt(noOfMonths/12);
let workExNoOfMonths = noOfMonths%12;
return workExNoOfYears+ " years, "+ workExNoOfMonths+" months";
}
function createEmailHtmlJs(messageJson)
{
let htmlMessage = '<!DOCTYPE html>'+
'<html lang="en">'+
'<head>'+
' <meta charset="UTF-8">'+
' <title>Job Application Information</title>'+
'</head>'+
'<body>'+
' <h4>Job application successfully submitted.</h4>'+
' <p>Please find below the details of your job application</p>'+
' <div class="row">'+
' <div class="col-sm-8">'+
' <div class="container">'+
' <h2>'+messageJson.jobName+'</h2>'+
' <table class="table">'+
' <tr>'+
' <td>Company</td>'+
' <td>'+messageJson.company+'</td>'+
' </tr>'+
' <tr>'+
' <td>Job Description</td>'+
' <td>'+messageJson.jobFunction+'</td>'+
' </tr>'+
' </tr>'+
' <tr>'+
' <td>Location</td>'+
' <td>'+messageJson.location+'</td>'+
' </tr>'+
' </table>'+
' </div>'+
' </div>'+
' <div class="col-sm-4">'+
' <img src="url(url_for_company_logo)" alt="'+messageJson.company+'">'+
' </div>'+
' </div>'+
'</body>'+
'</html>';
sendMessage(createMessage(htmlMessage, jobsnuEmail, messageJson.jobSeekerEmail, applicationEmailJsSubject));
}
function createEmailHtmlRec(messageJson)
{
let htmlMessage = '<!DOCTYPE html>'+
'<html lang="en">'+
'<head>'+
' <meta charset="UTF-8">'+
' <title>Applicant Information for Your Job Post</title>'+
'</head>'+
'<body>'+
' <h4>A user recently applied to your job '+messageJson.jobName +'</h4>'+
' <p>Please find below their application details.</p>'+
' <div class="row">'+
' <div class="col-sm-8">'+
' <div class="container">'+
' <h2>'+messageJson.applicantName+'</h2>'+
' <table class="table">'+
' <tr>'+
' <td>Email</td>'+
' <td>'+messageJson.applicantEmail+'</td>'+
' </tr>'+
' <tr>'+
' <td>Skill Set</td>'+
' <td>'+messageJson.applicantSkills+'</td>'+
' </tr>'+
' </tr>'+
' <tr>'+
' <td>Work Experience</td>'+
' <td>'+messageJson.workEx+'</td>'+
' </tr>'+
' </table>'+
' </div>'+
' </div>'+
' </div>'+
'</body>'+
'</html>';
sendMessage(createMessage(htmlMessage, jobsnuEmail, messageJson.recruiterEmail, applicationEmailRecSubject));
}
function createMessage(htmlMessage, fromId, toId, subject)
{
let message = {
from: fromId,
to: toId,
subject: subject,
html: htmlMessage
};
return message;
}
function sendEmailNotifJS(jobSeekerId, jobAppliedId)
{
console.log("Sending email notification to user " + jobSeekerId);
selectSql1 = "SELECT email from user_profile WHERE id ="+ jobSeekerId;
pool.query(selectSql1, function (selectErr1, selectResult1) {
if (selectErr1) {
console.log("Error fetching user details. See below for detailed error information.\n" + selectErr1.message);
console.log("-----DATABASE CONNECTIVITY ERROR-----\nKindly contact ADMIN.\n");
return;
} else if (selectResult1 == '') {
console.log("-----DATABASE ENTRY ERROR-----\nKindly contact ADMIN.\n" + JSON.stringify(responseJson));
return;
} else {
let jobSeekerEmail = selectResult1[0].email;
let selectSql2 = "SELECT job_post.job_name, employer.user_name, " +
"job_post.function, job_post.city, job_post.state," +
" job_post.country FROM job_post " +
"INNER JOIN employer ON employer.id = job_post.company_id " +
"INNER JOIN job_application ON job_application.job_post_id = job_post.id " +
"WHERE job_application.user_profile_id = "+jobSeekerId+ " AND job_application.job_post_id = "+jobAppliedId;
pool.query(selectSql2, function (selectErr2, selectResult2) {
if (selectErr2) {
console.log("-----DATABASE ERROR-----\nError fetching job details. See below for detailed error information.\n");
console.log("Error in query " + selectErr2.message);
return;
}
let htmlMessageJson = {
"jobSeekerEmail" : jobSeekerEmail,
"jobName": selectResult2[0].job_name,
"company": selectResult2[0].user_name,
"jobFunction" : selectResult2[0].function,
"location": selectResult2[0].city+", "+selectResult2[0].state+", "+selectResult2[0].country
};
createEmailHtmlJs(htmlMessageJson);
var responseJson = {
"dbError": 0,
"userId": jobSeekerId,
"jobId": jobAppliedId,
"notificationSent": 1
};
console.log("-----------Email Notification Sent------------\n" + JSON.stringify(responseJson));
return;
});
}
});
}
function sendEmailNotifRec(applicantId, jobId)
{
let selectSql1 = "SELECT email from user_profile where id = (SELECT posted_by_id " +
"from job_post WHERE id = "+jobId+");SELECT job_name, posted_by_id from job_post where id ="+jobId;
pool.query(selectSql1, function (selectErr1, selectResult1) {
if (selectErr1) {
console.log("Error fetching recruiter details. See below for detailed error information.\n" + selectErr.message);
console.log("-----DATABASE CONNECTIVITY ERROR-----\nKindly contact ADMIN.\n");
return;
} else {
let recruiterEmail = selectResult1[0][0].email;
let jobName = selectResult1[1][0].job_name;
let selectSqls = "SELECT js_skill_set.user_profile_id, js_skill_set.skill_id, " +
"skill_set.skill_name, user_profile.email, user_profile.first_name, " +
"user_profile.last_name FROM js_skill_set " +
"JOIN skill_set ON skill_set.id = js_skill_set.skill_id " +
"JOIN user_profile ON user_profile.id = js_skill_set.user_profile_id " +
"where js_skill_set.user_profile_id = "+applicantId+";" +
"SELECT PERIOD_DIFF(EXTRACT(YEAR_MONTH FROM end_date), EXTRACT(YEAR_MONTH FROM start_date)) + " +
"(CASE WHEN ABS((DAY(end_date)-DAY(start_date)) > 15) THEN 1 ELSE 0 END) as num_of_months " +
"from work_experience where user_profile_id = "+applicantId;
pool.query(selectSqls, function (selectErrs, selectResults) {
if (selectErrs) {
console.log("-----DATABASE ERROR-----\nError fetching job details. See below for detailed error information.\n");
console.log("Error in query " + selectErrs.message);
return;
}
let applicantSkills = "";
for(i in selectResults[0]){
let skill = JSON.stringify(selectResults[0][i].skill_name).split('"').join('');
applicantSkills += skill +", ";
}
let numOfMonths = 0;
for (i in selectResults[1]){
numOfMonths += parseInt(selectResults[1][i].num_of_months);
}
let workEx = calculateWorkEx(numOfMonths);
let htmlMessageJson = {
"recruiterEmail" : recruiterEmail,
"jobName": jobName,
"applicantId" : applicantId,
"applicantEmail" : selectResults[0][0].email,
"applicantName": selectResults[0][0].first_name + " "+ selectResults[0][0].last_name,
"applicantSkills" : applicantSkills.substring(0, applicantSkills.length - 2).trim('"'),
"workEx" : workEx
};
// console.log("htmlMessageJson "+JSON.stringify(htmlMessageJson));
createEmailHtmlRec(htmlMessageJson);
var responseJson = {
"dbError": 0,
"jobId": jobId,
"applicantId" : applicantId,
"applicantName": selectResults[0][0].first_name + " "+ selectResults[0][0].last_name,
"recruiterEmail" : recruiterEmail,
"notificationSent": 1
}
console.log("-----------Email Notification Sent------------\n" + JSON.stringify(responseJson));
return;
});
}
});
}
function sendMessage(message)
{
transporter.sendMail(message, function(err, info) {
if (err) {
console.log("ERROR IN SENDING MAIL.");
console.log(err)
} else {
console.log("SUCCESSFULLY SENT MAIL.");
console.log("MAIL INFO\n"+info);
}
});
}
// PATCH ROUTER FUNCTIONS
/* To reset user's password (to be called after
* answers have been verified for their correctness by FE)
* Request body params: - email -> user's email ID
* - password -> new password set by the user
* Returns: JSON object containing
* - passwordReset -> true/false depending on
* successfull/unsuccessful DB update, resp.
*/
app.patch('/resetPassword', function (req, res) {
let email = req.body.user.email;
let password = req.body.user.password;
// Update password in login table
let updateSql = 'UPDATE login SET password = ?' +
'where email = ?';
let updateSqlParams = [password, email];
pool.query(updateSql,updateSqlParams,function (err, result) {
if(err){
console.log('[UPDATE ERROR] - PASSWORD RESET',err.message);
res.send();
}
let htmlMessageString = '<!DOCTYPE html>'+
'<html lang="en">'+
'<head>'+
' <meta charset="UTF-8">'+
' <title>'+passwordResetSubject+'</title>'+
'</head>'+
'<body>'+
' <h4>Jobsnu Password Reset Successful</h4>'+
' <p>Your password has been successfully reset.</p>'+
' <p>Kindly use your new password to log in to jobsnu.com</p>'+
'</body>'+
'</html>';
let passwordResetMessage = createMessage(htmlMessageString, jobsnuEmail, email, passwordResetSubject);
sendMessage(passwordResetMessage);
// Output JSON format
var response = {
"email": email,
"passwordReset": true
};
console.log(JSON.stringify(response));
res.send(JSON.stringify(response));
});
});
// POST ROUTER FUNCTIONS
app.post('/applyJob', function (request,response) {
let userId = request.body.user.userId;
let jobId = request.body.user.jobId;
let insertSql = "insert into job_application(user_profile_id, job_post_id, application_date) VALUES (?,?,CURDATE())";
let insertSqlParams = [userId, jobId];
pool.query(insertSql, insertSqlParams, function (selectErr, selectResult, selectFields) {
if (selectErr) {
var postResponse = {
"dbError": 1,
"jobApplied": 0,
"emailSent" : false
}
console.log("Error in applying for job. See below for detailed error information.\n" + selectErr.message)
console.log("-----DATABASE CONNECTIVITY ERROR-----\nKindly contact ADMIN.\n");
response.send(JSON.stringify(postResponse));
} else {
sendEmailNotifJS(userId, jobId);
sendEmailNotifRec(userId, jobId);
var postResponse = {
"dbError": 0,
"jobApplied": 1,
"jobId": jobId,
"userId": userId,
"emailsSent" : true
}
console.log("-----------User " + userId +
" applied to job " + jobId +
" successfully------------\n");
response.send(JSON.stringify(postResponse));
}
});
});
app.post('/createJob', function (req, res) {
let jobName = req.body.job.jobName;
let postedByUserId = req.body.job.userId;
let jobDomain = req.body.job.jobDomain;
let companyIndustry = req.body.job.companyIndustry;
let jobFunction = req.body.job.jobFunction;
let jobDescription = req.body.job.jobDescription;
let city = req.body.job.city;
let state = req.body.job.state;
let country = req.body.job.country;
let jobType = req.body.job.jobType;
let skills = req.body.job.skills;
let skillsArr = skills.split(',');
let jobTypeVal;
if(jobType == "Internship" || jobType == "I")
jobTypeVal = "I";
else if(jobType == "Full-Time" || jobType == "F")
jobTypeVal = "F";
else if(jobType == "Part-Time" || jobType == "P")
jobTypeVal = "P";
let sql = "INSERT INTO job_post(job_name, posted_by_id, company_id, domain, industry, function," +
" description, city, state, country, job_type_id) VALUES (?,?,(select current_company_id " +
"from job_seeker_profile where user_profile_id="+parseInt(postedByUserId)+"),?,?,?,?,?,?,?,?);"
let sqlParams = [jobName, postedByUserId, jobDomain,
companyIndustry, jobFunction, jobDescription, city, state, country, jobTypeVal];
pool.query(sql,sqlParams, function (selectError, selectResult)
{
if(selectError) {
throw selectError;
}
jobId = selectResult.insertId;
for (let i=0; i < (skillsArr.length); i++) {
pool.query("SELECT id from skill_set where lower(skill_name)= ?", [skillsArr[i].toLowerCase().trim()], function (selErr, selRes) {
if(selErr)
throw selErr;
let skillId = selRes[0].id;
pool.query("insert into jp_skill_set(job_post_id, skill_id) values (?, ?)", [jobId, skillId], function (insErr, insRes) {
if(insErr)
throw insErr;
console.log("-----Updated skill set for new job post in DB-----");
});
});
}
var response = {
"jobAdded": 1,
"jobId": jobId
};
console.log("----------Job created successfully-----------");
console.log(response);
res.send(JSON.stringify(response));
});
});
app.post('/login', function(request, response){
let userEmail = request.body.user.email;
console.log("REQUEST.BODY\n"+ request.body);
console.log("REQUEST - Email: "+userEmail);
let selectSql = "select * from user_profile where email = '" + userEmail +"';";
pool.query(selectSql, function (selectErr, selectResult) {
if (selectErr) {
var loginResponse = {
"dbError" : 1,
"invalid": 0,
"verified": 1,
"userId": null,
"username": null,
"isRecruiter": null
}
console.log("Error fetching user details. See below for detailed error information.\n" + selectErr.message)
console.log("-----DATABASE CONNECTIVITY ERROR-----\nKindly contact ADMIN.\n");
response.send(JSON.stringify(loginResponse));
}
else if (selectResult == '') {
// return 0;
var loginResponse = {
"dbError" : 0,
"invalid": 0,
"verified": 1,
"userId": null,
"username": null,
"isRecruiter": null
}
console.log("-----DATABASE ENTRY ERROR-----\nKindly contact ADMIN.\n")
response.send(JSON.stringify(loginResponse));
}
else {
var loginResponse = {
"dbError" : 0,
"invalid": 0,
"verified": 1,
"userId": selectResult[0].id,
"username": selectResult[0].first_name,
"isRecruiter": selectResult[0].is_recruiter
}
console.log("-----------Login successful!------------\nLogging in user " + selectResult[0].first_name);
response.send(JSON.stringify(loginResponse));
}
});
});
app.post('/mfaLogin', function (req,res) {
console.log(req.body.user)
let email = req.body.user.email;
let password = req.body.user.password;
let otp = req.body.user.otp;
console.log("In LOGIN");
var selectSQL = "select email, password, verified, mfa_enabled from login where email = '" + email + "' and password = '" + password + "'";
// var addSqlParams = [req.query.emailid,req.query.password];
pool.query(selectSQL, function (err, result) {
if (err) {
console.log('[SELECT ERROR] - ', err.message);
return;
}
console.log(result)
if (result == '') {
console.log("Invalid credentials.");
let response = {
"invalid" : 1
}
res.send(JSON.stringify(response));
}
else if(!result[0].verified) // User has not yet verified their email account
{
// User E-mail ID Verification
let response = {
"invalid" : 0,
"verified" : 0,
"otp" : otp
}
console.log(response);
res.send(JSON.stringify(response));
}
else {
// selectSQL2 = "SELECT id FROM user_profile where "
if (result[0].mfa_enabled) {
console.log("IN VERIFIED & MFA_ENABLED");
let htmlMessageString =
"<html>" +
"<head>" +
"<title>" + otpEmailSubject + "</title>" +
"</head>" +
"<body>" +
"<div style=\"text-align: center\">" +
"<br><br><br><br>" +
"</div>" +
"<div style=\"margin:0 auto; width:600px; height:600px; text-align: center;\">" +
"<div style=\"margin:0 auto; width:600px; height:30px; text-align: center; background-color:#E7717D \"> " +
"</div>" +
"<div style=\" text-align: center; margin:0 auto; width:600px; height:200px; background-color:#C2CAD0 \">" +
"<img src=\"https://cdn.pixabay.com/photo/2015/01/08/18/26/write-593333_1280.jpg\" " +
"height = \"250px\" width=\"600px text-align: center\">" +
"</div>" +
"<div style=\"margin:0 auto; width:600px; height:370px; text-align: center;background-color:#C2CAD0 \">" +
"</div>" +
"<div style=\"position:absolute;left:580px;top:560px; width: 150px; height: 60px; display: block; color: #fff;background: #AFD275; font-size: 24px; line-height: 50px;text-align: center; \">" +
otp +
"</div>" +
"<div style=\" position:absolute;left:450px;top:450px; width:400px; height:300px; text-align: center; \">" +
"<p style=\" width:400px; height:300px; text-align: center;\">Kindly use the OTP below to log in to Jobsnu.<p>" +
"</div>" +
"<div style=\" font-size: 1px; position:absolute;left:352px;top:700px; width:600px; height:40px; background-color:#7E685A \"> " +
"*Terms & conditions apply."
"Do not share your the OTP or other personal details, such as user ID/password, with anyone, either over phone or through email." +
"</div>" +
"</div>" +
"</body>" +
"</html>";
let otpMessage = createMessage(htmlMessageString, jobsnuEmail, email, otpEmailSubject);
sendMessage(otpMessage);
var response = {
"invalid": 0,
"verified": 1,
"otp": otp,
"email": result[0].email
}
console.log("***************\nMFA RESPONSE\n***************\n" + JSON.stringify(response));
res.send(JSON.stringify(response));
}
else
{
var response = {
"invalid": 0,
"verified": 1,
"otp": -1,
"email": result[0].email
}
console.log("IN VERIFIED & !MFA_ENABLED");
console.log("***************\nLOGIN WITHOUT MFA RESPONSE\n***************\n" + JSON.stringify(response));
// res.send(JSON.stringify(response));
res.redirect(307, '/login');
}
}
});
});
app.post('/register', function (req, res) {
let email = req.body.user.email;
let firstName = req.body.user.firstName;
let lastName = req.body.user.lastName;
let dob = req.body.user.dob;
let gender = req.body.user.gender;
let primaryContact = req.body.user.primaryContact;
let secondaryContact = req.body.user.secondaryContact;
let insertSql = "IF NOT EXISTS (SELECT * FROM user_profile WHERE email = '"+email+"')" +
"INSERT INTO user_profile(email, first_name, " +
"last_name, dob, gender, primary_contact, secondary_contact, " +
"registration_date, is_recruiter) VALUES(?,?,?,?,?,?,?,CURDATE(),0) "+
"ELSE" +
"UPDATE user_profile " +
"SET first_name = ?, last_name = ?, gender = ?," +
"primary_contact = ?, secondary_contact = ? " +
"WHERE email = '"+email+"';";
let insertSqlParams = [email, firstName, lastName, dob, gender, primaryContact, secondaryContact];
pool.query(insertSql,insertSqlParams, function (err, result)
{
if(err) {
console.log('[INSERT ERROR] - ',err.message);
res.end("0");
return;
}
console.log("User added successfully.\n" + result);
});
var response = {
"userId" : result.insertId,
"email": email,
"firsName":firstName,
"lastName":lastName,
"dob": dob,
"gender": gender,
"primaryContact": primaryContact,
"secondaryContact": secondaryContact
};
// should show profile saved message/saved profile details
console.log(response);
res.send(JSON.stringify(response));
});
app.post('/setEducation', function (req, res) {
let userId = req.body.education.userId;
let eduLevel = req.body.education.eduLevel;
let eduField = req.body.education.eduField;
let institute = req.body.education.institute;
let startDate = req.body.education.startDate;
let endDate = req.body.education.endDate;
let percentage = req.body.education.percentage;
let insertSql = 'INSERT INTO education(user_profile_id, education_level, field, institute, ' +
'start_date, end_date, percentage) VALUES (?,?,?,?,?,?,?)';
let insertSqlParams = [userId, eduLevel, eduField, institute, dateFormat(startDate,"UTC:yyyy-mm-dd"), dateFormat(endDate, "UTC:yyyy-mm-dd"), percentage];
pool.query(insertSql,insertSqlParams, function (insertError, insertResult)
{
if(insertError) {
console.log('[INSERT ERROR] - EDUCATION DETAILS', insertError.message);
return;
}
console.log("Education details added successfully.\n", insertResult);
var responseJson = {
"userId": req.body.education.userId,
"eduLevel" : req.body.education.eduLevel,
"eduField" : req.body.education.eduField,
"institute" : req.body.education.institute,
"startDate" : req.body.education.startDate,
"endDate" : req.body.education.endDate,
"percentage" : req.body.education.percentage
};
// should show profile saved message/saved profile details
console.log("------------EDUCATION DETAILS RESPONSE----------\n"+responseJson);
res.end(JSON.stringify(responseJson));
});
});
app.post('/setMfa', function (request,response) {
let mfaEnabled = req.body.user.mfa;
updateSql = "update login set mfa_enabled = " + mfaEnabled;
pool.query(v, function (updateErr, updateResult, updateFields) {
if (updateErr) {
var setMfaResponse = {
"dbError" : 1,
"mfaSet": 0
}
console.log("Error updating MFA details. See below for detailed error information.\n" + updateErr.message)
console.log("-----DATABASE CONNECTIVITY ERROR-----\nKindly contact ADMIN.\n");
response.send(JSON.stringify(setMfaResponse));
}
else {
var setMfaResponse = {
"dbError" : 0,
"mfaSet": 1
}
console.log("-----------MFA enabled/disabled.------------\n");
response.send(JSON.stringify(setMfaResponse));
}
});
});
app.post('/setSecurityQuestions', function (req, res) {
let userId = req.body.user.userId;
let question1 = req.body.user.question1;
let answer1 = req.body.user.answer1;
let question2 = req.body.user.question2;
let answer2 = req.body.user.answer2;
let insertSql = 'INSERT INTO security_questions VALUES (?,?,?,?,?)';
let insertSqlParams = [userId, question1, answer1, question2, answer2];
pool.query(insertSql,insertSqlParams, function (insertError, insertResult)
{
if(insertError) {
console.log('[INSERT ERROR] - SECRET QUESTIONS', insertError.message);
return;
}
console.log("Secret questions for USER "+ userId+" updated successfully.\n", insertResult);
var responseJson = {
"userId" : userId,
"questionsUpdated" : true
};
console.log("------------SECRET QUESTIONS - RESPONSE----------\n"+JSON.stringify(responseJson));
res.end(JSON.stringify(responseJson));
});
});
app.post('/set_verification_status', function (req, res) {
let isVerified = req.body.user.isVerified;
let email = req.body.user.email;
let password = req.body.user.password;
if(isVerified) { // if user is verified (Verification OTP entered was correct)
// Change verification status of user in login table
let sqlQuery = 'UPDATE login SET verified = ? where email = ? and password = ?' ;
let sqlQueryParams = [isVerified, email, password];
pool.query(sqlQuery, sqlQueryParams,
function (err, result)
{
if(err){
console.log('[UPDATE ERROR] - ',err.message);
res.send(err.message);
return;
}
console.log(result);
});
let response = {
"verified" : 1
}
console.log("OK");
console.log(response);
res.send(JSON.stringify(response));
// res.send(response);
}
else
{
let response = {
'verified' : 0
}
res.send(JSON.stringify(response))
}
// console.log(response);
});
app.post('/setWorkExperience', function (req, res) {
let userId = req.body.work.userId;
let startDate = req.body.work.startDate;
let endDate = req.body.work.endDate;
let company = req.body.work.company;
let description = req.body.work.description;
let designation = req.body.work.designation;
let location = req.body.work.location;
let insertSql = 'INSERT INTO work_experience(user_profile_id, start_date, end_date, ' +
'company, description, designation, location) VALUES (?,?,?,?,?,?,?)';
let insertSqlParams = [userId, dateFormat(startDate, "UTC:yyyy-mm-dd"), dateFormat(endDate, "UTC:yyyy-mm-dd"), company, description, designation, location];
pool.query(insertSql,insertSqlParams, function (insertError, insertResult)
{
if(insertError) {
console.log('[INSERT ERROR] - WORK EXPERIENCE DETAILS', insertError.message);
// res.end("0");
return;
}
console.log("Work experience details added successfully.\n", insertResult);
var responseJson = {
"userId" : userId,
"startDate" : startDate,
"endDate" : endDate,
"company" : company,
"description" : description,
"designation" : designation,
"location" : location
};
// should show profile saved message/saved profile details
console.log("------------WORK EXPERIENCE RESPONSE----------\n"+responseJson);
res.end(JSON.stringify(responseJson));
});
});
app.post('/skillAssessmentScore', function (request,response) {
let userId = request.body.user.userId;
let skillName = request.body.user.skillName;
let answersArr = request.body.user.answersArr;
let correct = 0;
let score = 0;
let total = answersArr.length;
if(!skillAssessJson.hasOwnProperty(skillName))
{
let responseJson = {
"entryError" : true,
"questions" : null
}
response.send(JSON.stringify(responseJson));
return;
}
let questionsArr = [];
for(let i in skillAssessJson[skillName]) {
let questionArrEle = skillAssessJson[skillName][i];
let questionJson = {
"id": questionArrEle.id,
"answer": questionArrEle.answer
}
questionsArr.push(questionJson);
}
let questionJson;
let answerJson;
for (let id in answersArr)
{
questionJson = questionsArr[id];
answerJson = answersArr[id];
if(questionJson.id == answerJson.id && questionJson.answer == answerJson.answer)
correct += 1;
}
score = correct/total*100;
let updateSql = "update js_skill_set set skill_level = ? " +
"where user_profile_id = ? and skill_id = (SELECT id from skill_set where skill_name = ?)";
let updateSqlParams = [score, userId, skillName];
pool.query(updateSql, updateSqlParams, function (updateErr, updateRes) {
if(updateErr) {
var responseJson = {
"dbError": 1,
"userId": userId,
"score": score,
"scoreUpdated": false
};
console.log("\n-----DB ERRORS-----\nSkill score " +
"not updated in DB.\nKindly contact DB Admin.\n" + updateErr.message);
response.send(JSON.stringify(responseJson));
return;
}
else
{
var responseJson = {
"dbError" : 0,
"userId" : userId,
"score" : score,
"scoreUpdated" : true
}
console.log("---------SCORE for skill "+skillName+" is "+ score +"---------\n"+ JSON.stringify(responseJson));
response.send(JSON.stringify(responseJson));
}
});
});
app.post('/verify', function (req, res) {
let email = req.body.user.email;
let password = req.body.user.password;
let otp = req.body.user.otp;
// Add user to login table
let addSql = 'INSERT INTO login (email, password, otp) VALUES(?, ?, ?)';
let addSqlParams = [email, password, otp];
pool.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log('[INSERT ERROR] - VERIFY',err.message);
res.end("0");
return;
}
let htmlMessageString =
"<html>" +
"<head>" +
"<title>" + verificationEmailSubject + "</title>" +
"</head>" +
"<body>" +
"<div style=\"text-align: center\">" +
"<br><br><br><br>" +
"</div>" +
"<div style=\"margin:0 auto; width:600px; height:600px; text-align: center;\">" +
"<div style=\"margin:0 auto; width:600px; height:30px; text-align: center; background-color:#E7717D \"> " +
"</div>" +
"<div style=\" text-align: center; margin:0 auto; width:600px; height:200px; background-color:#C2CAD0 \">" +
"<img src=\"https://cdn.pixabay.com/photo/2015/01/08/18/26/write-593333_1280.jpg\" height = \"250px\" width=\"600px text-align: center\">" +
"</div>" +
"<div style=\"margin:0 auto; width:600px; height:370px; text-align: center;background-color:#C2CAD0 \">" +
"</div>" +
"<div style=\"position:absolute;left:580px;top:560px; width: 150px; height: 60px; display: block; color: #fff;background: #AFD275; font-size: 24px; line-height: 50px;text-align: center; \">" +
otp +
"</div>" +
"<div style=\" position:absolute;left:450px;top:450px; width:400px; height:300px; text-align: center; \">" +
"<p style=\" width:400px; height:300px; text-align: center;\">" +
" Kindly use the code below to complete your registration process on Jobsnu.<p>" +
"</div>" +
"<div style=\" font-size: 1px; position:absolute;left:352px;top:700px; width:600px; height:40px; background-color:#7E685A \"> " +
"*Terms & conditions apply."+
"Do not share your the OTP or other personal details, such as user ID/password, with anyone, either over phone or through email." +
"</div>" +
"</div>" +
"</body>" +
"</html>";
let verificationMessage = createMessage(htmlMessageString, jobsnuEmail, email, verificationEmailSubject);
sendMessage(verificationMessage);
// Output JSON format
var response = {
"email": email,
"password": password,
"verified": 0, // 0: Not verified, 1: Verified; becomes 1 after verification
"otp": otp
};
console.log("OK");
console.log(result);
console.log(response);
res.send(JSON.stringify(response));
// res.send(response);
});
});
// GET ROUTER FUNCTIONS
app.get('/getUserChats', function (request,response) {
let userId = request.query.userId;
console.log("Chat user Id is"+userId)
chatkit.getUserRooms({
userId: userId,
})
.then((res) => {
response.send(res)
console.log(res);
}).catch((err) => {
console.log(err);
response.status(400).send([])
});
})
app.get('/getUserName', function (request,response) {
let userId = request.query.userId;
chatkit.getUser({
id: userId,
})
.then((res) => {
response.send(res)
console.log(res);
}).catch((err) => {
console.log(err);
response.status(400).send("")
});
})
app.get('/companyDetails', function (request,response) {
let companyId = request.query.companyId;
let selectSql = "select * from employer where id = " + companyId;
pool.query(selectSql, function (selectErr, selectResult) {
if (selectErr) {
var loginResponse = {
"dbError" : 1,
"userId": null
}
console.log("Error fetching employer details. See below for detailed error information.\n" + selectErr.message)
console.log("-----DATABASE CONNECTIVITY ERROR-----\nKindly contact ADMIN.\n");
response.send(JSON.stringify(loginResponse));
}
else if (selectResult == '') {
var loginResponse = {
"dbError" : 0,
"userId": null
}