-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.js
575 lines (520 loc) · 15.8 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
//imports and require statements.
const express = require('express');
const request = require('request');
const bodyParser = require('body-parser');
const connection = require('./database');
const crypto = require('crypto');
const session = require('express-session');
const tf = require('@tensorflow/tfjs');
require('@tensorflow/tfjs-node');
const encoder = require('@tensorflow-models/universal-sentence-encoder');
const similarity = require('compute-cosine-similarity');
const path = require('path');
require('dotenv').config();
/*THESE ARE ALL THE FUNCTIONS USED INSIDE THE SERVER SIDE CODE */
//generating salt for password hashing
var genSalt = function(length){
return crypto.randomBytes(Math.ceil(length/2)).toString('hex').slice(0,length);
};
//generate normal hash
var normalHash = function(userPassword){
const normalHash = crypto.createHash('sha512').update(userPassword).digest('hex');
return normalHash;
};
//generate salted hash
var sha512 = function(password,salt){
var hash = crypto.createHmac('sha512',salt);
hash.update(password);
var value = hash.digest('hex');
return{
salt:salt,
passwordHash:value
};
};
//a function that uses similarity function above to generate similarity dictionary
var get_cosine_similarity_matrix = function(user_matrix,all_matrix){
//key = user_matrix_sentence_index, value = list(cosine_similarity_score) with all_matrix
var return_dict = {};
for (i=0;i<user_matrix.length;i++){
var local_user_matrix = [];
for (j=0;j<all_matrix.length;j++){
var s = similarity(user_matrix[i],all_matrix[j]);
local_user_matrix.push(s);
}
return_dict[i] = local_user_matrix;
}
return return_dict;
};
//getting embeddings for a list of sentences
var get_embeddings = async function(list_sentences){
const model = await encoder.load();
const embeddings = await model.embed(list_sentences);
const a = embeddings.arraySync();
return a;
};
/*ALL THE SERVER SIDE CODE AND ENDPOINTS BEGIN HERE*/
//initiating server and app
const app = express();
const port = 3000;
//trying to implement sessions
app.use(session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
loggedin: false,
user_email: null,
first_name: null,
last_name: null
}));
//
app.use('/login',express.static('public'));
//allow sending and receiving different objects
app.use(bodyParser.urlencoded({
extended:true
}));
app.use(bodyParser.json());
//allow cross domain communication
var allowCrossDomain = function(req,res,next){
res.header('Access-Control-Allow-Origin','*');
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers','Content-Type');
next();
};
app.use(allowCrossDomain);
//default pathname redirects to login page
app.get('/',function(req,resp){
console.log(req.session);
//redirect to main page if logged in
if (req.session.loggedin){
resp.redirect('/main');
}
//redirect to login page if not
else{
resp.redirect('/login');
}
});
//db test endpoint for seeing the data in the db. WILL BE REMOVED AFTER DEV IS COMPLETE
app.route('/test_db').get(function(req,res,next){
connection.query(
"SELECT * from `users`",
function(error,results,fields){
if (error) throw error;
res.json(results);
}
);
});
//db test endpoint for seeing the data in the current db
app.route('/test_db2').get(function(req,res,next){
connection.query(
"SELECT * from `current`",
function(error,results,fields){
if (error) throw error;
res.json(results);
}
);
});
//db test endpoint for seeing the data in history db
app.route('/test_db3').get(function(req,res,next){
connection.query(
"SELECT * from `history`",
function(error,results,fields){
if (error) throw error;
res.json(results);
}
);
});
//db get user endpoint for login verification
app.get('/check_user',function(req,res,next){
const user_email = req.query.email;
const my_pass = req.query.password;
const pass = normalHash(my_pass);
//make sql query
connection.query("SELECT first_name,last_name,email from `users` WHERE email='"+user_email+"' AND password_hash='"+pass+"'",function (error,results,fields) {
//some internal sql error only
if (error) throw error;
else{
console.log("reached");
//user found
if (results[0]){
//continue here and bring in authentication and redirect logic here
//remove the redirect and stuff from index.js. Only keep the logic for displaying errors. Otherwise, console.log everything.
req.session.loggedin = true;
req.session.user_email = user_email;
req.session.first_name = results[0].first_name;
req.session.last_name = results[0].last_name;
res.send(results);
}
//user not found
else{
//error display logic to be handled at client
console.log("user not found.");
res.send(results);
}
}
}
);
});
// endpoint that gets first and last name of user
app.get("/get_user_info", function(req, res) {
if (req.session.loggedin) {
// Get values from the session data
user_email = req.session.user_email;
/* alternate way Vivek - res.send(req.session) */
// get user info from database
connection.query("SELECT first_name,last_name,email from `users` WHERE email='" + user_email + "'", function (error, results, fields) {
//some internal sql error only
if (error) throw error;
else {
console.log("reached");
//user found
if (results[0]) {
//send info to client
res.type("application/json");
res.send(results);
}
//user not found
else {
//error display logic to be handled at client
console.log("user not found.");
res.send(results);
}
}
});
}
else{
res.send("You need to login to access this endpoint.")
}
});
app.get("/get_task",function(req, res, next){
if (req.session.loggedin) {
const user_email = req.session.user_email;
// get user info from database
connection.query("SELECT task, due_date, priority from `current` WHERE email='" + user_email + "' ORDER BY due_date,priority", function (error, results, fields) {
//some internal sql error only
if (error) throw error;
else {
console.log("reached");
//user found
if (results[0]) {
//send info to client
res.type("application/json");
res.send(results);
}
//user not found
else {
//error display logic to be handled at client
console.log("user not found.");
res.send(results);
}
}
});
}
else{
res.send("You need to login to access this endpoint")
}
});
/*
//temp
app.get("/temp",function(req,res,next){
connection.query(
//"SHOW CREATE TABLE `history`",
//"ALTER TABLE `history` DROP PRIMARY KEY",
"TRUNCATE TABLE `current`",
function(error,results,field){
if (error) throw error;
else{
res.json(results);
console.log("DROPPED");
}
}
);
});
*/
//an endpoint that renders cutomized homepage for the logged in user. REMEMBER, all the users will not have a common homepage.
app.get('/main',function(req,res,next){
if (req.session.loggedin){
//res.send("<h1>Hello "+req.session.first_name+" "+req.session.last_name+"!</h1>");
res.sendFile(path.join(__dirname,'public','main.html'));
}
else{
//res.send("You need to login to access tyhis page.");
res.redirect('/');
}
});
//signout endpoint - have a signout button in the client and bind this endpoint with it.
//PENDING BINDING ON CLIENT SIDE.
app.get('/signout',function(req,res,next){
req.session.loggedin = false;
req.session.user_email = null;
req.session.first_name = null;
req.session.last_name = null;
res.redirect("/"); // redirects to login after signout
});
//an endpoint that will edit the task in the database
app.post("/edit_task",function(req,res,next){
if (req.session.loggedin){
const data = req;
const user_email = req.session.user_email;
const old_task = data.body.oldTask;
const old_due_date = data.body.oldDueDate;
const old_priority = data.body.oldPriority;
const new_task = data.body.newtask;
const new_due_date = data.body.newDueDate;
const new_priority = data.body.newPriority;
connection.query(
"UPDATE`current` SET task='"+new_task+"',priority='"+new_priority+"',due_date='"+new_due_date+"' WHERE email='"+user_email+"' AND task='"+old_task+"'",
function(error,results,fields){
if (error) throw error;
else{
connection.query(
"SELECT * FROM `history` WHERE email='"+user_email+"' AND task='"+new_task+"'",
function(error,results,fields){
if (error) throw error;
else{
console.log(results);
if (results[0]){
connection.query(
"UPDATE `history` SET counter = counter + 1 WHERE email='"+user_email+"' AND task='"+new_task+"'",
function (error,results,fields) {
if (error) throw error;
else{
console.log("task found in history.counter increased.");
res.status(200).send("Task edited.");
}
}
);
}
else {
connection.query(
"INSERT INTO `history` (email,task,counter) VALUES('"+user_email+"','"+new_task+"',1)",
function (error,results,fields) {
if (error) throw error;
else{
console.log("task not found in history.now added.");
res.status(200).send("Task edited.");
}
}
);
}
}
}
);
}
}
);
}
});
//db post endpoint for deleting your account. create a button on user homepage and bind this endpoint with it.
app.post('/remove_db',function(req,res,next){
const data = req;
const user_email = data.body.email;
if (user_email != req.session.user_email) {
throw error;
}
req.session.loggedin = false;
req.session.user_email = null;
req.session.first_name = null;
req.session.last_name = null;
//INSERT A DELETE QUERY HERE
connection.query(
"DELETE from `users` WHERE email='"+user_email+"'",
function(error,results,fields){
if (error){
throw error;
}
else{
console.log("user deleted");
connection.query(
"DELETE from `current` WHERE email='"+user_email+"'",
function(error,results,fields){
if (error){
throw error;
}
else{
console.log("current tasks deleted")
}
}
)
res.redirect("/");
}
});
});
//db post endpoint for creating new user for create account
app.post('/post_db',function (req,res,next) {
const data = req;
const first_name = data.body.first_name;
const last_name = data.body.last_name;
const email = data.body.email;
const password = data.body.password;
const password_hash = normalHash(password); //512 hashed
const uid_password = sha512(password,genSalt(16)).passwordHash; //salted unique hash
connection.query(
"INSERT into `users` VALUES('"+first_name+"','"+last_name+"','"+email+"','"+password_hash+"','"+uid_password+"')",//finish the query
function(error,results,fields){
if (error){
res.status(400).send("user exists.");
}
else{
res.status(200).send("user added.");
}
}
);
});
//gets the history which will be used for recommending most frequently added task to users
app.get('/get_history',function(req,res,next){
if (req.session.loggedin) {
const email = req.session.user_email;
connection.query(
"SELECT * FROM `history` WHERE email='"+email+"'ORDER BY counter DESC LIMIT 10",
function (error, results, fields) {
if (error) throw error;
else {
res.json(results);
}
}
);
}
else{
res.send("You need to log in to access this endpoint")
}
});
//delete task post endpoint
//NOTE: This enpoint will be bound to a button in client code and will expect a TASK exactly as stored in db
app.post('/delete_task',function(req,res,next){
if (req.session.loggedin){
const data = req;
const email = req.session.user_email;
const task = data.body.task;
connection.query(
"DELETE FROM `current` WHERE email='"+email+"'AND task='"+task+"'",
function(error,results,fields){
if (error) throw error;
else{
res.status(200).send("task deleted from current table");
}
}
);
}
});
//an endpoint for getting recommendations using machine learning
app.get('/get_custom_recommendations',function(req,res,next){
//get all the tasks FOR ALL USERS from history table using history database
//get all the tasks FOR CURRENTLY LOGGED IN user using history database
//vectorize using a common algorithm (TF,IDF,HF)
//recommend the top one using cosine similarity
//add a priority weightage while making recommendations
if (req.session.loggedin){
const email = req.session.user_email;
const all_tasks = [];
const user_tasks = [];
//get all historic tasks
connection.query(
"SELECT * FROM `history` WHERE email!='"+email+"'",
function(error,results,fields){
if (error) throw error;
else{
//get tasks for current user
connection.query(
"SELECT * FROM `history` WHERE email='"+email+"'",
function(err,my_results,fiel){
if (err) throw err;
else{
for (i=0;i<results.length;i++){
all_tasks.push(results[i].task.toLowerCase());
}
for (i=0;i<my_results.length;i++){
user_tasks.push(my_results[i].task.toLowerCase());
}
console.log(all_tasks);
console.log(user_tasks);
const b = get_embeddings(all_tasks);
b.then(function(result){
const a = get_embeddings(user_tasks);
a.then(function(done){
const my_results = get_cosine_similarity_matrix(done,result);
//get the best results and send it
var return_list = [];
for (var key in my_results){
//key = index of user tasks; value = array of all tasks
for (k=0;k<my_results[key].length;k++) {
var return_object = {};
return_object["user_task"] = user_tasks[key];
return_object["recommended_task"] = all_tasks[k];
var sim = my_results[key][k];
sim = sim.toFixed(2);
sim = parseFloat(sim);
const percent = sim * 100;
return_object["similarity"] = percent;
return_list.push(return_object);
}
}
console.log(JSON.stringify(return_list,null,4));
res.json(return_list);
});
});
}
}
);
}
}
);
}
else{
res.send("You must log in to access this endpoint.")
}
});
//adds a new task in the database as a post request
app.post('/add_task',function (req,res,next) {
const data = req;
const email = req.session.user_email;
const task = data.body.task;
const dueDate = data.body.dueDate;
const priority = data.body.priority;
connection.query(
"INSERT into `current` (email, task, due_date, priority) VALUES('"+email+"','"+task+"','"+dueDate+"','"+priority+"')", //finish the query
function(error,results,fields){
if (error){
throw error;
}
else{
//add history
connection.query(
"SELECT * FROM `history` WHERE email='"+email+"' AND task='"+task+"'",
function(error,results,fields){
if(error) throw error;
else{
console.log(results);
if (results[0]){
//increase count by 1 as the task already exists for the users
connection.query(
"UPDATE `history` SET counter = counter + 1 WHERE email='"+email+"' AND task='"+task+"'",
function (error,results,fields) {
if (error) throw error;
else{
console.log("task found in history.counter increased.");
res.status(200).send("Task added.");
}
}
);
}
else {
connection.query(
"INSERT INTO `history` (email,task,counter) VALUES('"+email+"','"+task+"',1)",
function (error,results,fields) {
if (error) throw error;
else{
console.log("task not found in history.now added.");
res.status(200).send("Task added.");
}
}
);
}
}
}
);
}
}
);
});
//listen
app.listen(port, () => console.log('Listening on port '+port));