-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
1393 lines (1257 loc) · 53.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
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
// // // BASIC // // //
require('dotenv').config();
const express = require("express")
const ejs = require('ejs')
const bodyParser = require('body-parser') // helps us get information inputed by users
const https = require("https")
const passport = require('passport');
const session = require('express-session')
var mySqlStore = require('express-mysql-session')(session);
const mysql = require('mysql')
var LocalStrategy = require('passport-local').Strategy;
const Connection = require("mysql/lib/Connection")
const flash = require('connect-flash');
const bcrypt = require('bcrypt');
const e = require('connect-flash');
const multer = require('multer')
const otpGenerator = require('otp-generator')
const nodemailer = require("nodemailer");
const {
resolve
} = require('path');
const {
reject
} = require('underscore');
const saltRounds = 10;
// var GoogleStrategy = require('passport-google-oauth20').Strategy;
const {
google
} = require("googleapis")
const CLIENT_ID = '1097006599803-fcbi72qsh19a5qaerbe7gao16g2bv2uf.apps.googleusercontent.com'
const CLIENT_SECRET = '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'
const REDIRECT_URL = 'https://developers.google.com/oauthplayground'
const REFRESH_TOKEN = '1//04UNbZIgfjWRqCgYIARAAGAQSNwF-L9Ir0kW6qH1pPOyHPuCBZwN55GuO91mil6xa8UEzTZBoDWpZYgdZ2UwXW0BlMlCXdYbhljo'
// INITIALIZATION
const app = express()
app.use(express.static(__dirname + '/static'))
app.set('view engine', 'ejs')
app.use(bodyParser.urlencoded({
extended: true
})) // url encoded is used to get information from html forms
// CREATE CONNECTION
// var con = mysql.createConnection({
// host: "studiviadb.cnreudh8065g.ap-south-1.rds.amazonaws.com",
// port: "3306",
// user: "auspy",
// password: "password",
// database: "studiviaDB"
// })
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "password",
database: "studiviaDB"
})
// CONNECT
con.connect(function (err) {
if (err) throw err;
console.log("connected!")
// TABLE
})
// SESSION
var sessionStore = new mySqlStore({}, con);
app.use(session({
key: 'session_cookie_name',
secret: ['verysecret', 'notsoimportant', 'highlyprobably', 'secretisneeded'],
name: "studiviacookieitis",
store: sessionStore,
cookie: {
sameSite: true,
},
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(passport.authenticate('session'));
app.use(flash());
var loginStatus = false
// // // UPLOADED/UPLOADING FILES // // //
const storage = multer.diskStorage({
destination: function (req, file, cb) {
// maybe store file based on username
cb(null, __dirname + '/static/uploads')
},
filename: function (req, file, cb) {
const uniqueSuffix = Date.now()
cb(null, uniqueSuffix + file.originalname)
}
})
const upload = multer({
storage: storage,
// fileFilter: (req, file, cb) => {
// // The function should call `cb` with a boolean
// // to indicate if the file should be accepted
// if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == " application/pdf") {
// cb(null, true);
// } else {
// cb(null, false);
// return cb(new Error('Only .png, .jpg and .jpeg format allowed!'));
// }
// // You can always pass an error if something goes wrong:
// cb(new Error('I don\'t have a clue!'))
// },
limits: {
fieldNameSize: "150bytes",
fieldSize: "50MB"
}
})
// // // AUTHENTICATION // // //
var currentUser, errorMsg = ''
var savedArr = [],
uploadArr = [],
cartArr = []
passport.use('local', new LocalStrategy({
usernameField: 'username',
passwordField: 'userPass',
passReqToCallback: true, // allows us to pass back the entire request to the callback
}, function (req, username, userPass, cb) {
let sql = "SELECT *,password,username as uid FROM userLedger WHERE username = " + con.escape(username) + "or email =" + con.escape(username)
con.query(sql, function (err, user) {
console.log(user);
if (err) {
return cb(err);
}
if (!user.length) {
errorMsg = 'Wrong username or password'
console.log('error', errorMsg)
return cb(null, false);
} else if (userPass) {
bcrypt.compare(userPass, user[0].password, function (err, result) {
if (result === false) {
console.log('Wrong password');
errorMsg = 'Wrong password'
return cb(null, false);
} else {
var mailChar = /@/
if (mailChar.test(String(username))) {
req.session["user"] = user[0].uid
} else {
req.session["user"] = username
currentUser = req.session.user
// reset the arrays so that current user docs can be filled
savedArr = []
uploadArr = []
cartArr = []
findDocs()
findDocs('uploaded') // to load upload docs of current user on login
findDocs('cart')
loginStatus = true
console.log("req.session", req.session, "req.session.user", req.session.user);
followFunc('follower', req.session.user)
followFunc('following', req.session.user)
dashFunc(req.session.user)
req.session.regenerate((err) => {}) // to regenrate session
return cb(null, user[0], req.flash('message', 'welcome'));
}
}
});
}
});
}));
passport.serializeUser(function (user, cb) {
cb(null, {
username: user.username
});
});
passport.deserializeUser(function (user, cb) {
return cb(null, user);
});
// // // GOOGLE OAUTH // // //
// passport.use(new GoogleStrategy({
// clientID: process.env.CLIENT_ID,
// clientSecret: process.env.CLIENT_SECRET,
// callbackURL: "http://localhost:3000/auth/google/studivia"
// // userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo"
// },
// function (accessToken, refreshToken, profile, cb) {
// let sql = "SELECT * FROM docsLedger WHERE userId = " + profile.id
// let name = profile.displayName.split(" ")
// let firstName = name[0]
// let lastName = name[1]
// con.query(sql, (err, users) => {
// if (err) {
// console.log('google error');
// return cb(err);
// }
// if (!users.length) {
// let insertUser = "INSERT INTO docsLedger(userId,firstName,lastName) VALUES(" + con.escape(profile.id) + "," + con.escape(firstName) + "," + con.escape(lastName) + ")"
// con.query(insertUser, (err) => {
// console.log('added new user');
// })
// }
// console.log('welcome, from google');
// return cb(null, users, req.flash('message', 'welcome'))
// })
// }
// ));
const oAuth2Client = new google.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URL)
oAuth2Client.setCredentials({
refresh_token: REFRESH_TOKEN
})
async function sendMail(sendTo, data) {
try {
const accessToken = await oAuth2Client.getAccessToken()
const transport = nodemailer.createTransport({
service: "gmail",
auth: {
type: "OAuth2",
user: "[email protected]",
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
refreshToken: REFRESH_TOKEN,
accessToken: accessToken
}
})
const mailOptions = {
from: 'STUDIVIA <[email protected]>',
to: sendTo,
subject: 'testing nodemailer',
text: data,
}
const result = await transport.sendMail(mailOptions)
return result
} catch (error) {
return error
}
}
// sendMail(user[0].Email).then(result => console.log('Email sent...',result))
// .catch((error)=> console.log(error.message))
// // // REGISTER PAGE/ SIGN UP PAGE/SETUP MAIL CHIMP // // //
var verifyinput, newotp
app.post('/register/code', (req, res) => {
// generate new otp
newotp = otpGenerator.generate(6, {
upperCaseAlphabets: false,
specialChars: false,
lowerCaseAlphabets: false
})
console.log("userEmail", req.body.email, "newotp", newotp);
userEmail = req.body.email
// send otp to user email
sendMail(userEmail, "your otp is" + newotp).then(result => console.log('Email sent...', result))
.catch((error) => console.log(error.message))
// save otp to table for 5 mins and then delete
let sqladd = "INSERT INTO otpLedger(otp) VALUES(" + con.escape(newotp) + ")"
con.query(sqladd, (err) => {
if (err) throw err;
console.log("otp added to table");
})
// let gettime = "SELECT timeadded FROM otpLedger WHERE otp ="+con.escape(newotp)
// con.query(gettime,(err,time)=>{
// if (err) throw err;
// console.log("time",time);
// })
var currentDate = new Date()
var expiryDate = new Date(currentDate.getTime() - 2 * 6000)
// console.log("expiryDate",expiryDate);
let deleteotp = "DELETE FROM otpLedger WHERE valid = false or timeadded < " + con.escape(expiryDate)
con.query(deleteotp, (err) => {
if (err) throw err;
// console.log("otp validity time expired");
})
})
var otpvalidity = false
app.post('/register/verify', (req, res) => {
otpvalidity = false
let sql = "SELECT otp FROM otpLedger where valid = true"
con.query(sql, (err, otps) => {
if (err) throw err;
console.log("otps", otps);
console.log("otp", req.body.userotp);
verifyinput = req.body.userotp
for (let i = 0; i < otps.length; i++) {
if (verifyinput != otps[i].otp) {
otpvalidity = false
} else {
otpvalidity = true
}
}
if (otpvalidity == true) {
console.log("verified email");
let sql = "UPDATE otpLedger SET valid = false WHERE otp = " + con.escape(verifyinput)
con.query(sql, (err) => {
console.log("removed used otp from database");
})
} else {
console.log("invalid otp, try again");
}
})
})
app.post('/register', (req, res, next) => {
var username = req.body.username
var email = req.body.userMail
// to check if the user is already registered
let sqlCheck = "SELECT * FROM userLedger WHERE username =" + con.escape(username) + " or email =" + con.escape(email)
con.query(sqlCheck, (err, users) => {
if (err) throw err;
if (users != '') {
// console.log(users[0].Username,'users');
if (users[0].Username == username) {
console.log('username already exists');
res.redirect('/register')
} else if (users[0].Email == email) {
console.log('email already registered');
res.redirect('/register')
}
} else {
if (otpvalidity == true) {
console.log(req.body);
bcrypt.hash(req.body.userPass, saltRounds, function (err, hash) {
if (err) throw err;
// console.log('register form details', req.body);
let year = Number(req.body.userGradYear.substring(0, 4))
// to add user to user ledger
let sql = "INSERT INTO userLedger(firstname,lastname,email,password,username,university,graduation_year,course) VALUES(" + con.escape(req.body.firstName) + "," + con.escape(req.body.lastName) + "," + con.escape(email) + "," + con.escape(hash) + "," + con.escape(req.body.username) + "," + con.escape(req.body.userUniv) + "," + con.escape(year) + "," + con.escape(req.body.userCourse) + ")"
con.query(sql, function (err) {
if (err) throw err;
console.log('added to user ledger');
res.redirect('/login.html') // we can add a if else in login and use a var to describe situation. like if coming after login we will ask them to login to get started. on writing wrong password we will show error.
})
// to create new table for new user
let newUserTable = "CREATE TABLE " + username + "(docID varchar(16) PRIMARY KEY,saved BIT DEFAULT NULL,cart BIT DEFAULT NULL,uploaded BIT DEFAULT NULL,purchased BIT DEFAULT NULL,lastUpdated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP)"
let userFTable = "CREATE TABLE " + username + "F( `username` VARCHAR(16) NOT NULL , `follower` BOOLEAN NOT NULL DEFAULT FALSE , `following` BOOLEAN NOT NULL DEFAULT FALSE , `lastUpdated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP , PRIMARY KEY (`username`)) ENGINE = InnoDB;"
let userPTable = "CREATE TABLE " + username + "P( `postid` VARCHAR(20) NOT NULL , `liked` BOOLEAN NOT NULL DEFAULT FALSE , `shared` BOOLEAN NOT NULL DEFAULT FALSE , `saved` BOOLEAN NOT NULL DEFAULT FALSE , PRIMARY KEY (`postid`(16))) ENGINE = InnoDB;"
con.query(newUserTable, function (err) {
if (err) throw err;
})
con.query(userFTable, function (err) {
if (err) throw err;
console.log("created follow table for", username);
})
con.query(userPTable, function (err) {
if (err) throw err;
console.log("created posts table for", username);
})
})
} else {
console.log('invalid otp, try again');
res.redirect('/register')
}
}
})
// // to send user data to mailchimp
// // api key: 903d6a06801c5965a6ac93819f85b1fd-us14
// //374202afae
// let data1 = {
// members: [{
// email_address: req.body.userMail,
// status: "subscribed",
// merge_fields: {
// FNAME: req.body.firstName,
// LNAME: req.body.lastName
// }
// }]
// }
// let dataJson = JSON.stringify(data1)
// const mailchimpUrl = "https://us14.admin.mailchimp.com/lists/374202afae"
// const options = {
// method: "POST",
// headers: {
// 'Content-Type': 'application/json'
// },
// auth: "studiviaishere:process.env.MAILCHIMP_API"
// }
// const request = https.request(mailchimpUrl, options, function (response) {
// response.on("data", function (data) {
// console.log(data);
// })
// })
// res.sendFile(__dirname + '/html/dashboard.html')
// request.write(dataJson)
// request.end()
})
app.get('/register', (req, res, next) => {
res.render('register', {
page: 'Register'
})
})
// // // LOGIN // // //
app.get('/login.html', function (req, res, next) {
res.render('login', {
page: 'Login',
errorHtml: errorMsg
})
})
app.post('/login.html', passport.authenticate('local', {
failureRedirect: '/login.html'
}),
function (req, res) {
console.log('in dash', req.session.user);
return res.redirect('/dashboard.html')
});
// // // LISTEN, SERVER START // // //
const port = 8000
app.listen(port, () => {
console.log('server started yes',port)
})
// // // ALL PAGES // // //
// need to think of the naming convention of url
app.get('/', function (req, res) {
res.sendFile(__dirname + '/html/index.html')
})
// app.get('/auth/google', (res, req) => {
// passport.authenticate('google', {
// scope: ['profile']
// });
// })
// app.get('/auth/google/studivia',
// passport.authenticate('google', {
// failureRedirect: '/login'
// }),
// function (req, res) {
// res.redirect('/dashboard.html');
// // Successful authentication, redirect home.
// });
app.get('/index.html', function (req, res) {
req.flash('message', 'Success!!');
res.sendFile(__dirname + '/html/index.html')
})
app.get('/student_reviews.html', function (req, res) {
res.render('reviews')
})
app.get('/rankings.html', function (req, res) {
res.sendFile(__dirname + '/html/rankings.html')
})
app.get('/pricing.html', function (req, res) {
res.render('pricing')
})
var userFeedPosts = [],
userFeed
function feedPosts(user) {
// gives all the posts of users our current user is following
var feedSql = ''
console.log("users i follow", followingUsers, followingUsers.length);
if (followingUsers.length > 0) {
feedSql = "SELECT * FROM postLedger WHERE username =" + con.escape(followingUsers[0].username)
// console.log("sql for =1", feedSql);
if (followingUsers.length > 1) {
for (let i = 1; i < followingUsers.length; i++) {
feedSql = feedSql + " OR username =" + con.escape(followingUsers[i].username)
console.log("sql for >1", feedSql);
}
}
// to get posts of profiles followed by user
con.query(feedSql, (err, posts) => {
console.log('sql in query', feedSql);
if (err) throw err;
if (posts.length) {
userFeedPosts = posts // stores the posts needed to show on dashboard
console.log("posts added to feed");
likedStatus(user) // problem with this is that we have to reload page to get the data. maybe we can use async await to render page when this has finished processing
displayComments() // display comments
} else {
userFeedPosts = []
}
console.log("userFeedPosts", userFeedPosts);
})
}
}
var postsLiked = {},
postComments = {} // can later on merge as i get more understanding of json
function likedStatus(user) {
// takes all the posts being shown on feed and gives their like status in a dictionary type datatype
postsLiked = {}
// forms dictionary of postid: likedStatus
for (let i = 0; i < userFeedPosts.length; i++) {
let checkLiked = "SELECT * FROM " + userFeedPosts[i].postId + " WHERE username =" + con.escape(user)
console.log("posts on feed", userFeedPosts[i]);
console.log("id of posts on feed", userFeedPosts[i].postId);
con.query(checkLiked, (err, rows) => {
if (err) throw err;
console.log("liked status rows", rows);
if (rows.length) {
if (rows[0].liked == true) {
postsLiked[String(userFeedPosts[i].postId)] = true //String doesn't matter
// console.log(0,"status true");
} else {
postsLiked[userFeedPosts[i].postId] = false
// console.log(0,"status false");
}
}
// else{
// postsLiked = {}
// }
})
postStatusCount(userFeedPosts[i].postId, 'liked')
}
}
var postLikeCount
function postStatusCount(postid, statusName) {
postLikeCount = 0
// to be used with liked status on dashboard
// to count total users who liked/shared/commented on the post
let totalLikes = "SELECT * FROM " + postid + " WHERE " + statusName + " = true"
con.query(totalLikes, (err, users) => {
if (err) throw err;
if (users.length) {
postLikeCount = users.length
console.log("total users who", statusName, postLikeCount);
}
})
}
var userComment = {}
function displayComments() {
// return new Promise((resolve,reject)=>{
postComments = {}
for (let i = 0; i < userFeedPosts.length; i++) {
userComment = {}
let sql = "SELECT * FROM " + userFeedPosts[i].postId + "P"
con.query(sql, (err, comments) => {
if (err) throw err;
// console.log(comments);
if (comments.length) {
// agar comments he to aise bhardo
for (let j = 0; j < comments.length; j++) {
// this creates a json storage for sno and username,comment
userComment[comments[j].sno] = [comments[j].username, comments[j].comment]
}
postComments[userFeedPosts[i].postId] = userComment
} else {
// agar comments nhi he to khali array
postComments[userFeedPosts[i].postId] = false
}
// json storage created in above loop is stored as value for postid(key). so now we have all comments with users which can be called for each post using its postid.
// console.log("userComment after loop",userComment);
// console.log("post comments",postComments);
})
}
// resolve()
// })
}
const dashValues = {}
function dashFunc(user = currentUser) {
let savedSql = "SELECT * FROM " + user + " WHERE saved = 1"
let uploadSql = "SELECT * FROM " + user + " WHERE uploaded = 1"
let cartSql = "SELECT * FROM " + user + " WHERE cart = 1"
let userPosts = "SELECT * FROM postLedger WHERE userid = " + con.escape(user) + "or username = " + con.escape(user) // total posts by user
con.query(savedSql, (err, savedCount) => {
if (err) throw err;
dashValues["saved"] = savedCount.length
})
con.query(uploadSql, (err, uploadCount) => {
if (err) throw err;
dashValues["upload"] = uploadCount.length
})
con.query(cartSql, (err, cartCount) => {
if (err) throw err;
dashValues["cart"] = cartCount.length
})
con.query(userPosts, (err, postCount) => {
if (err) throw err;
dashValues["posts"] = postCount.length
})
}
app.get('/dashboard.html', (req, res) => {
if (req.isAuthenticated()) {
console.log("req.flash()", req.flash('message'));
dashFunc()
feedPosts(req.session.user)
// console.log("userFeedPosts in dash", userFeedPosts);
// if (userFeedPosts == []) {
// postComments = null
// }
console.log("dashValues", dashValues);
// console.log("feed-posts liked status in dash", postsLiked);
// console.log("post comments in dash", postComments);
// return res.send('nice')
res.render('dashboard', {
usernameHtml: req.session.user,
savedHtml: dashValues['saved'],
uploadHtml: dashValues['upload'],
cartHtml: dashValues['cart'],
postHtml: dashValues['posts'],
followerHtml: followerUsers.length,
followingHtml: followingUsers.length,
userFeedPostsHtml: userFeedPosts,
postsLikedHtml: postsLiked,
likeCountHtml: postLikeCount,
postCommentsHtml: postComments
})
loginStatus = true
} else {
loginStatus = false
return res.redirect('/login.html')
}
})
app.get('/contact-us.html', function (req, res) {
res.render('contact')
})
app.get('/checkout.html', function (req, res) {
if (req.isAuthenticated()) {
res.render('checkout', {
page: 'Checkout'
})
}else{
res.redirect('/login.html')
}
})
app.get('/logout', (req, res) => {
loginStatus = false
errorMsg = ''
req.logout()
req.session.destroy((err) => {})
res.redirect('/')
})
// // // POST REQUESTS // // //
// // // ON UPLOADING A DOC // // //
var latestDocId
// , fileSize = 0
// app.use(bodyParser.json());
// app.post('/sell-docs/size',(req,res)=>{
// console.log("size",req.body.size);
// fileSize = req.body.size
// })
app.get('/sell-docs.html', function (req, res) {
res.render('sell_docs', {
loginStatusHtml: loginStatus
})
})
app.post('/sell-docs.html', upload.single('upDocs'), function (req, res, next) {
// upload(req, res, function (err) {
// if (err instanceof multer.MulterError) {
// // A Multer error occurred when uploading.
// console.log('error in multer')
// } else if (err) {
// // An unknown error occurred when uploading.
// console.log('error in post sell-docs')
// }
// Everything went fine.
console.log(req.file.path);
// UPLOADED DOC DETAILS
var docName = req.body.name
var docUniv = req.body.university
var docType = req.body.docType
var docLang = req.body.langName
var docCour = req.body.courseName
var docSubj = req.body.subName
var docTopic = req.body.topic
var docYear = req.body.year
var docDesc = req.body.desc
var docPrice = req.body.setPrice
var docEarn = req.body.earnPer
console.log(req.body)
console.log(req.body.upDocs)
console.log(req.body.upDocs)
console.log("req.file", req.file.path);
// FOR DOCID : getting last input in docsLedger so that we can increment it whenever new doc is added
var docCount
var digits = "0000"
var lastEntry = "SELECT DocId FROM `docsLedger` ORDER BY `lastUpdated` DESC LIMIT 1;"
con.query(lastEntry, function (err, neededId) {
if (err) throw err;
// to get last 4 digits of DocId
var lastId = String(neededId[0].DocId)
var last4digits = lastId.substring(lastId.length - 4)
var neededNum = parseInt(last4digits) + 1
// to convert final number into 4 digits and get docID-last-4-digits
docCount = (digits.substring(String(neededNum).length) + neededNum)
var docId = (docName.substring(0, 3) + docUniv.substring(0, 3) + docSubj.substring(0, 3) + docLang.substring(0, 2) + docCount).toUpperCase()
latestDocId = docId
// ADD DOC TO MAIN LEDGER AND NEWUSER TABLE
var addDocToLedger = "INSERT INTO docsLedger(DocName,username,DocId,University,Doc_Type,language,course,subject,topic,year,description,price,docpath) VALUES (" + con.escape(docName) + "," + con.escape(req.session.user) + "," + con.escape(docId) + "," + con.escape(docUniv) + "," + con.escape(docType) + "," + con.escape(docLang) + "," + con.escape(docCour) + "," + con.escape(docSubj) + "," + con.escape(docTopic) + "," + con.escape(docYear) + "," + con.escape(docDesc) + "," + con.escape(docPrice) + "," + con.escape(req.file.path) + ")"
var addToNewUser = "INSERT INTO " + req.session.user + "(docID, uploaded) VALUES(" + con.escape(docId) + ", 1)"
con.query(addDocToLedger, function (err) {
if (err) throw err;
console.log('added name', docCount)
})
con.query(addToNewUser, function (err) {
if (err) throw err;
console.log('added to new user')
})
console.log(req.body)
})
res.render('sell_docs_2')
// })
})
// TO GET ANS OF DOC RELATED QUESTIONS
app.post('/sell-docs-2', function (req, res) {
var ans1 = req.body.docQues1
var ans2 = req.body.docQues2
var ans3 = req.body.docQues3
var ans4 = req.body.docQues4
var ans5 = req.body.docQues5
var ans6 = req.body.docQues6
var addAns = "UPDATE `docsLedger` SET `ans1` = " + con.escape(ans1) + ",`ans2`= " + con.escape(ans2) + ", `ans3`= " + con.escape(ans3) + ", `ans4`= " + con.escape(ans4) + ", `ans5`= " + con.escape(ans5) + ", `ans6`= " + con.escape(ans6) + " WHERE `docsLedger`.`DocId` = " + con.escape(latestDocId) + ";"
con.query(addAns, function (err) {
if (err) throw err;
console.log('updated')
})
findDocs('uploaded') // will be added to send for verification of step 3 when i create one
res.render('sell_docs_3')
})
app.post('/draft', (req, res) => {
findDocs('uploaded')
res.redirect('/my-docs.html')
})
// SEND FOR VERIFICATION
app.post('/sell-docs3', (req, res) => {
// send data to verification team
sendMail("[email protected]", "new document added to be verified" + latestDocId).then((result) => {
console.log('Email sent to verification team...', result)
res.redirect("/my-docs.html")
})
.catch((error) => {
console.log(error.message)
res.redirect("/dashboard.html")
})
})
// // // STUDY MATERIAL DOCS // // //
// LATEST DOCS
var currentUserDocs = {},
studyMatDocs
app.get('/study_material.html', function (req, res) {
if (req.isAuthenticated()) {
var latestDocs = 'SELECT DocId,DocName,Username,Course,University,Doc_Type,Subject,Topic,Price,docpath FROM `docsLedger` WHERE verified = true ORDER BY lastUpdated DESC LIMIT 20;'
con.query(latestDocs, function (err, neededInfo) {
if (err) throw err;
studyMatDocs = neededInfo
for (let i = 0; i < neededInfo.length; i++) {
// console.log(neededInfo)
let sql = "SELECT * FROM " + req.session.user + " WHERE docID =" + con.escape(neededInfo[i].DocId) + ";"
con.query(sql, (err, doc) => {
if (err) throw err;
if (doc.length) {
currentUserDocs[neededInfo[i].DocId] = [doc[0].saved, doc[0].cart]
} else {
currentUserDocs[neededInfo[i].DocId] = [null, null]
}
loginStatus = true
// return res.send('currentUserDocs in',currentUserDocs,"studyMatDocs",studyMatDocs)
})
}
setTimeout(() => {
console.log('currentUserDocs in', currentUserDocs, "studyMatDocs", studyMatDocs);
res.render("study_material", {
neededInfoList: studyMatDocs,
currentUserDocsHtml: currentUserDocs
})
}, 300)
})
// to get values for new pdfs
} else {
res.redirect('/login.html')
loginStatus = false
}
})
// // // DOCS DESC // // //
var docDescList
// to get data of document clicked from client and then sql
app.use(express.json({
limit: '1mb'
}))
app.post('/descLinkClicked', function (req, res) {
console.log("clicked document details", req.body);
var docNeeded = "SELECT * FROM docsLedger WHERE docid = " + con.escape(req.body.docid)
con.query(docNeeded, function (err, docDesc) {
if (err) throw err;
docDescList = docDesc
// console.log(docDescList);
})
})
// console.log('outside',docDescList);
// to use data sent by client on button click and create needed page using ejs template
app.get('/doc-desc', function (req, res) {
// console.log('inside',docDescList);
if (req.isAuthenticated()) {
return res.render('docsViewer', {
docDescList1: docDescList[0],
documentName: docDescList[0].DocName,
course: docDescList[0].Course,
subject: docDescList[0].Subject,
university: docDescList[0].University,
topic: docDescList[0].Topic,
year: docDescList[0].Year,
type: docDescList[0].Doc_Type
})
}else{
res.redirect('/login.html')
}
})
// // // ADD TO CART OR SAVED DOCS // // //
addToSavCarServer('/addCart', 'cart')
addToSavCarServer('/saveDoc', 'saved')
function addToSavCarServer(url, savCar) {
app.post(url, function (req, res) {
// console.log(req.body.docid);
let idSearch = "SELECT saved,cart,uploaded,purchased FROM " + req.session.user + " WHERE docid =" + con.escape(req.body.docid)
con.query(idSearch, (err, savedColValue) => {
if (savedColValue != "") {
var savCarBothNull = savedColValue[0].saved == null && savedColValue[0].cart == null
var upPurBothNull = savedColValue[0].uploaded == null && savedColValue[0].purchased == null
var upOrPurNotNull = savedColValue[0].uploaded != null || savedColValue[0].purchased != null
if (savCar == 'saved') {
var onClick1 = savedColValue[0].saved == null && savedColValue[0].cart != null
var onClickBothNull = savedColValue[0].saved != null && savedColValue[0].cart == null
} else {
var onClick1 = savedColValue[0].saved != null && savedColValue[0].cart == null
var onClickBothNull = savedColValue[0].saved == null && savedColValue[0].cart != null
}
}
// console.log(savedColValue);
if (err) throw err;
else if (savedColValue == "") {
// when ye id he hi nhi table me
// console.log('situation 1 and saved+cart value is', savedColValue[0]);
// console.log('will add', req.body.docid);
let sql = "INSERT INTO " + req.session.user + "(docid," + savCar + ") VALUES(" + con.escape(req.body.docid) + ",1)"
con.query(sql, (err) => {
if (err) throw err;
console.log('inserted', req.body.docid, 'to findDocs')
})
findDocs()
} else if ((savedColValue[0].saved != null && savedColValue[0].cart != null) || (onClickBothNull && upOrPurNotNull)) {
// when saved aur cart dono 1 he and button click hua. so, ab ek ko null karna he
if (req.body.extra == 'save-for-later') {
let sql = "UPDATE " + req.session.user + " SET cart = NULL WHERE docid =" + con.escape(req.body.docid)
con.query(sql, (err) => {
if (err) throw err;
console.log('updated null in cart for', req.body.docid, 'beacuse already in saved')
})
} else if (req.body.extra == 'move-to-cart') {
let sql = "UPDATE " + req.session.user + " SET saved = NULL WHERE docid =" + con.escape(req.body.docid)
con.query(sql, (err) => {
if (err) throw err;
console.log('updated null in saved for', req.body.docid, 'beacuse already in cart')
})
} else {
let sql = "UPDATE " + req.session.user + " SET " + savCar + " = NULL WHERE docid =" + con.escape(req.body.docid)
con.query(sql, (err) => {
if (err) throw err;
console.log('updated null in ' + savCar + ' for', req.body.docid, 'for cart')
})
}
findDocs()
findDocs('cart')
// console.log('situation 2 and saved+cart value is', savedColValue[0],'+ sql is',sql);
// console.log('will update', req.body.docid);
} else if (onClick1 || (savCarBothNull && upOrPurNotNull)) {
// when saved ya cart dono me se ek 1 he and dusre ka button click hua OR saved + cart dono null he but uploaded and purchased me se koi null nhi he. so, ab null wale ko 1 karna he
// console.log('condition 4', onClick1);
// console.log('situation 3 and saved+cart value is', savedColValue[0]);
if (req.body.extra == 'move-to-cart') {
let sql = "UPDATE " + req.session.user + " SET " + savCar + " = 1,saved = null WHERE docid =" + con.escape(req.body.docid)
con.query(sql, (err) => {
if (err) throw err;
console.log('updated 1 in ' + savCar + 'for', req.body.docid, 'and removed this from saved')
// will check count of both again
})
} else if (req.body.extra == 'save-for-later') {
let sql = "UPDATE " + req.session.user + " SET " + savCar + " = 1, cart = null WHERE docid =" + con.escape(req.body.docid)
con.query(sql, (err) => {
if (err) throw err;
console.log('updated 1 in ' + savCar + 'for', req.body.docid, 'and removed from cart')
})
} else {
let sql = "UPDATE " + req.session.user + " SET " + savCar + " = 1 WHERE docid =" + con.escape(req.body.docid)
con.query(sql, (err) => {
if (err) throw err;
console.log('updated 1 in ' + savCar + 'for', req.body.docid, 'in', req.session.user)
})
}
findDocs()
findDocs('cart')
} else if ((onClickBothNull || savCarBothNull) && (upPurBothNull)) {
// when is id me dono null ya phir jo 1 tha uska button click hua to ab wo bhi null he. lekin delete tabhi hoga agar uploaded and purchased dono null he
let sql = "DELETE FROM " + req.session.user + " WHERE docid =" + con.escape(req.body.docid)
// console.log('situation 4 and saved+cart value is', savedColValue[0]);
con.query(sql, (err) => {
if (err) throw err;
console.log('removed', req.body.docid, 'from table')
})
findDocs()
}
})
})
}
// // // SHOW SAVED DOCS and UPLOADED DOCS IN MY_DOCS // // //
function findDocs(docs = 'saved') {
if (docs == 'cart') {
cartArr = []
}
savedArr = [] // since saved docs can be removed we need to reset the list and count again unlike uploaded which remains same after running once
// i want to run this only when a new document is uploaded or server is started again
// and for saved whenever user clicks on saved button and on server restart
//?? ?? ?? agar saved docs badh jae to for loop boht bar chalega jissse system slow ho skta he. kya isse solve karne ka koi tarika he?
let sql = " SELECT docid FROM " + currentUser + " WHERE " + docs + " =1"
con.query(sql, (err, neededId) => {
if (err) throw err;
console.log(sql, neededId)
neededId.forEach((item, index) => {
let sql = "SELECT DocId,DocName,Username,Course,year,University,Doc_Type,Subject,Topic,Price FROM `docsLedger` WHERE docid =" + con.escape(item.docid)
con.query(sql, (err, neededInfo) => {
if (err) throw err;