-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
747 lines (563 loc) · 16.5 KB
/
app.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
//<----------------------Importing all required modules --------->
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require("passport");
const passportLocalMongoose = require("passport-local-mongoose");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const FacebookStrategy = require("passport-facebook");
const findOrCreate = require("mongoose-findorcreate");
const path = require("path");
const multer = require("multer");
const GridFsStorage = require("multer-gridfs-storage");
const Grid = require("gridfs-stream");
const methodOverride = require("method-override");
const crypto = require("crypto");
const checksum_lib = require("./checksum/checksum");
const config = require("./checksum/config");
const flash = require("connect-flash");
const _ = require("lodash");
//Using app as express instance
const app = express();
//setting public folder as default folder for assets
app.use(express.static("public"));
//setting view engine
app.set("view engine", "ejs");
// connecting Middleware
app.use(
bodyParser.urlencoded({
extended: true,
})
);
app.use(bodyParser.json());
app.use(methodOverride("_method"));
app.use(
session({
secret: process.env.SECRET,
// cookie: { maxAge: 60000 },
resave: false,
saveUninitialized: false,
})
);
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
///------------------creating connection with mongoDB database--------------------->
const mongoURI =
"mongodb+srv://grc_sr:Western@[email protected]/devclubDB";
const devclubDB = mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify:false
});
const conn = mongoose.connection;
mongoose.set("useCreateIndex", true);
//initiate GridFs
let gfs;
conn.once("open", () => {
// init stream
gfs = new mongoose.mongo.GridFSBucket(conn.db, {
bucketName: "uploads",
});
});
//cretate storage engine tp store gridfs elements
// const storage = new GridFsStorage({
// db: devclubDB,
// file: (req, file) => {
// return new Promise((resolve, reject) => {
// crypto.randomBytes(16, (err, buf) => {
// if (err) {
// return reject(err);
// }
// const filename = buf.toString("hex") + path.extname(file.originalname);
// const fileInfo = {
// filename: filename,
// bucketName: "uploads",
// };
// resolve(fileInfo);
// });
// });
// },
// });
// const upload = multer({ storage });
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './public/uploads/')
},
filename: function (req, file, cb) {
let ext = path.extname(file.originalname)
cb(null,Date.now() + ext)
}
});
const upload = multer ({
storage: storage,
fileFilter: (req,file,callback)=>{
if(file.mimetype="application/pdf"){
callback(null,true);
}else{
console.log("Only PDF formats are allowed");
callback(null,false);
}
},
limits: {
fileSize: 10485760
}
})
//Defining Storage Schemas to use it later
const userDetails = new mongoose.Schema({
name: String,
password: String,
facebookId: String,
googleId: String,
imageUrl: {
type: String,
},
username: String,
department: String,
year: String,
sem: String,
systemAdmin: Boolean,
});
//Schema for storing files
const fileSchema = new mongoose.Schema({
fileName: String,
department: String,
yearOfStudy: String,
semester: String,
subject: String,
unit: Number,
displayName: String,
uploadedBy:String
});
//using local mongoose plugin for session authentication.
userDetails.plugin(passportLocalMongoose);
userDetails.plugin(findOrCreate);
const Details = new mongoose.model("Detail", userDetails);
const File = new mongoose.model("File", fileSchema);
//Searialise and deserialise passport sessions.
passport.serializeUser(function (user, done) {
done(null, user.id);
});
passport.deserializeUser(function (id, done) {
Details.findById(id, function (err, user) {
done(err, user);
});
});
//Defining google and facebook strategy to authenticate using google and facebook auth.
passport.use(
new GoogleStrategy(
{
clientID: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
callbackURL: "http://localhost:3000/auth/google/herokuApp",
userProfileURL: "https://www.googleapis.com/oauth2/v3/userinfo",
},
function (accessToken, refreshToken, profile, cb) {
Details.findOrCreate(
{ googleId: profile.id },
{
username: profile.emails[0].value,
googleId: profile.id,
name: profile.displayName,
imageUrl: profile.photos[0].value,
department: "Enter your Department",
year: "Enter year of study ",
sem: "enter semester ",
},
function (err, user) {
return cb(err, user);
}
);
}
)
);
passport.use(
new FacebookStrategy(
{
clientID: process.env.FACEBOOK_APP_ID,
clientSecret: process.env.FACEBOOK_APP_SECRET,
callbackURL: "https://grcsdevelopersclub.tech/auth/facebook/herokuApp",
profileFields: ["id", "displayName", "photos", "email"],
},
function (accessToken, refreshToken, profile, cb) {
Details.findOrCreate(
{ facebookId: profile.id },
{
username: profile.emails[0].value,
facebookId: profile.id,
name: profile.displayName,
imageUrl: `https://graph.facebook.com/${profile.id}/picture?access_token=${accessToken}`,
department: "Enter your Department",
year: "Enter year of study ",
sem: "enter semester ",
},
function (err, user) {
return cb(err, user);
}
);
}
)
);
//Initialising the routes
//home route for rendering index.js
app.get("/", (req, res) => {
res.render("index");
});
app.get("/comingsoon",(req,res)=> {
res.render("comingsoon");
});
//route for handelling online-compilers.
// let editorLang = "python";
// app.get("/online-compiler", (req, res) => {
// if (req.isAuthenticated()) {
// res.render("online-compiler", {
// language: editorLang,
// });
// } else {
// res.redirect("/login");
// }
// });
// app.post("/online-compiler", (req, res) => {
// editorLang = req.body.Lang;
// res.render("online-compiler", {
// language: editorLang,
// });
// });
//Register route to register through google and facebook
app.get("/register", (req, res) => {
res.render("register");
});
//Login route to login through google and facebook auth
app.get("/login", (req, res) => {
res.render("login", { message: req.flash("message") });
});
//Handelling post request after login.
app.post("/login", (req, res, next) => {
passport.authenticate("local", {
successRedirect: "/profile",
failureRedirect: "/login",
})(req, res, next);
});
//Google authentication route sent to google
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"],
})
);
app.get(
"/auth/google/herokuApp",
passport.authenticate("google", {
failureRedirect: "/login"
// successRedirect: "/profile"
}),
function (req, res) {
// Successful authentication, redirect home.
res.redirect("/profile");
}
);
//Facebook authentication using api
app.get(
"/auth/facebook",
passport.authenticate("facebook", { scope: ["email"] })
);
app.get(
"/auth/facebook/herokuApp",
passport.authenticate("facebook", {
failureRedirect: "/login",
}),
function (req, res) {
// Successful authentication, redirect home.
res.redirect("/profile");
}
);
//Profile route
app.get("/profile", async (req, res) => {
if (req.isAuthenticated()) {
// materialArray = File.find({}).toArray();
res.render("profile", {
name: req.user.name,
imageUrl: req.user.imageUrl,
email: req.user.username,
department: req.user.department,
year: req.user.year,
sem: req.user.sem,
message: req.flash("message"),
});
} else {
res.redirect("/login");
}
});
//Profile update route
app.get("/profileUpdate", (req, res) => {
if (req.isAuthenticated()) {
// materialArray = File.find({}).toArray();
res.render("profileUpdate", {
name: req.user.name,
imageUrl: req.user.imageUrl,
email: req.user.username,
department: req.user.department,
year: req.user.year,
sem: req.user.sem,
});
} else {
res.redirect("/login");
}
});
app.post("/profileUpdate", (req, res) => {
console.log(req.user);
Details.findOneAndUpdate(
{ _id: req.user._id },
{
$set: {
department: req.body.department,
year: req.body.yearOfStudy,
sem: req.body.sem,
name: req.body.name,
},
},
(err, file) => {
if (!err) {
req.flash("message", "Successfully updated profile");
res.redirect("/profile");
} else {
req.flash("message", err);
}
}
);
});
//route for rendering payment interface
app.get("/paynow", (req, res) => {
res.render("donation");
});
//callback function for paytm payment gateway
app.post("/callback", (req, res) => {
// Route for verifiying payment
var body = "";
req.on("data", function (data) {
body += data;
});
req.on("end", function () {
var html = "";
var post_data = qs.parse(body);
// received params in callback
console.log("Callback Response: ", post_data, "\n");
// verify the checksum
var checksumhash = post_data.CHECKSUMHASH;
// delete post_data.CHECKSUMHASH;
var result = checksum_lib.verifychecksum(
post_data,
config.PaytmConfig.key,
checksumhash
);
console.log("Checksum Result => ", result, "\n");
// Send Server-to-Server request to verify Order Status
var params = { MID: config.PaytmConfig.mid, ORDERID: post_data.ORDERID };
checksum_lib.genchecksum(params, config.PaytmConfig.key, function (
err,
checksum
) {
params.CHECKSUMHASH = checksum;
post_data = "JsonData=" + JSON.stringify(params);
var options = {
hostname: "securegw-stage.paytm.in", // for staging
// hostname: 'securegw.paytm.in', // for production
port: 443,
path: "/merchant-status/getTxnStatus",
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": post_data.length,
},
};
// Set up the request
var response = "";
var post_req = https.request(options, function (post_res) {
post_res.on("data", function (chunk) {
response += chunk;
});
post_res.on("end", function () {
console.log("S2S Response: ", response, "\n");
var _result = JSON.parse(response);
if (_result.STATUS == "TXN_SUCCESS") {
res.send("payment sucess");
} else {
res.send("payment failed");
}
});
});
// post the data
post_req.write(post_data);
post_req.end();
});
});
});
//payment handelling route through post paytm.
app.post("/paynow", (req, res) => {
// Route for making payment
var paymentDetails = {
amount: req.body.amount,
customerId: req.body.phone,
customerEmail: req.body.email,
customerPhone: req.body.phone,
};
if (
!paymentDetails.amount ||
!paymentDetails.customerId ||
!paymentDetails.customerEmail ||
!paymentDetails.customerPhone
) {
res.status(400).send("Payment failed");
} else {
var params = {};
params["MID"] = config.PaytmConfig.mid;
params["WEBSITE"] = config.PaytmConfig.website;
params["CHANNEL_ID"] = "WEB";
params["INDUSTRY_TYPE_ID"] = "Retail";
params["ORDER_ID"] = "TEST_" + new Date().getTime();
params["CUST_ID"] = paymentDetails.customerId;
params["TXN_AMOUNT"] = paymentDetails.amount;
params["CALLBACK_URL"] = "http://gentle-lowlands-90024.herokuapp.com/callback";
params["EMAIL"] = paymentDetails.customerEmail;
params["MOBILE_NO"] = paymentDetails.customerPhone;
checksum_lib.genchecksum(params, config.PaytmConfig.key, function (
err,
checksum
) {
var txn_url = "https://securegw-stage.paytm.in/theia/processTransaction"; // for staging
// var txn_url = "https://securegw.paytm.in/theia/processTransaction"; // for production
var form_fields = "";
for (var x in params) {
form_fields +=
"<input type='hidden' name='" + x + "' value='" + params[x] + "' >";
}
form_fields +=
"<input type='hidden' name='CHECKSUMHASH' value='" + checksum + "' >";
res.writeHead(200, { "Content-Type": "text/html" });
res.write(
'<html><head><title>Merchant Checkout Page</title></head><body><center><h1>Please do not refresh this page...</h1></center><form method="post" action="' +
txn_url +
'" name="f1">' +
form_fields +
'</form><script type="text/javascript">document.f1.submit();</script></body></html>'
);
res.end();
});
}
});
//Route to store all files from the admins.
app.get("/store", (req, res) => {
// res.render("store",{message:req.flash("message")});
if (req.isAuthenticated()&& req.user.systemAdmin===true) {
res.render("store",{message:req.flash("message"),username:req.user.username});
} else {
res.redirect("/login");
}
});
app.get("/zoom",(req,res)=>{
res.render("zoom");
});
app.post("/store", upload.single("file"), (req, res) => {
const file = new File({
fileName: req.file.filename,
department: req.body.department,
yearOfStudy: req.body.yearOfStudy,
semester: req.body.semester,
subject: req.body.subject,
unit: req.body.unit,
displayName: req.body.displayName,
uploadedBy:req.body.userName,
message: req.flash("message"),
});
file.save((err) => {
if (!err) {
req.flash("message", "Sucessfully saved file details");
res.redirect("/store");
} else {
req.flash("message", err);
}
});
});
//Logout session trigerring
app.get("/logout", (req, res) => {
req.logout();
req.flash("message", "You are logged out successfully");
res.redirect("/login");
});
//Finding special file using filename
app.get("/files/:fileName", (req, res) => {
File.find({fileName: req.params.fileName},(err,data)=>{
if(err){
console.log(err)
}
else{
// console.log(data);
var path= __dirname+'/public/uploads/'+data[0].fileName;
res.download(path);
}
})
//Code for storing in MOnogoDB using grid Fs.
// gfs.find({ filename: req.params.fileName }).toArray((err, file) => {
// //check if files exist
// if (!file[0] || file.length === 0) {
// return res.status(404).json({
// success: false,
// message: "No Files Available",
// });
// }
// if (
// file[0].contentType === "image/jpeg" ||
// file[0].contentType === "application/pdf" ||
// file[0].contentType === "image/jpg" ||
// file[0].contentType === "image/png"
// ) {
// gfs.openDownloadStreamByName(req.params.fileName).pipe(res);
// } else {
// res.status(404).json({
// err: "Not an Image",
// });
// }
// });
});
//Viewing resources for specific branches.
app.get("/resources", (req, res) => {
res.render("resources");
// if (req.isAuthenticated()) {
// res.render("resources");
// } else {
// res.redirect("/login");
// }
});
app.post("/resources", (req, res) => {
const year = req.body.year;
const subjectValue = req.body.subject;
res.render("subject", { subject: subjectValue, yearOfStudy: year });
});
//Finding all resources using unit year and branch.
app.post("/resources/:year/subject/:subject", (req, res) => {
const year = req.params.year;
const subjectValue = req.params.subject;
const unitNo = req.body.unit;
File.find(
{ subject: subjectValue, unit: unitNo, yearOfStudy: year },
(err, files) => {
res.render("material", { files: files });
}
);
});
//Redirecting all 404 error to this custom error page.
app.use(function (req, res, next) {
res.status(404);
if (req.accepts("html")) {
res.render("404");
return;
}
});
//Setting port Dynamically
let port = process.env.PORT || 3000;
//Listening on custom port.
app.listen(port, (req, res) => {
console.log("Server is active on port " + port);
});