-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
681 lines (534 loc) · 14 KB
/
index.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
//Routing Mechanism - URL Define Here.
const express = require('express');
//Mongo Object
var ObjectId = require('mongodb').ObjectID;
//Express Only Get Data If Body-Parser Is Worked.
//To Get Value Of Any Control Body-Parser Is Compulsory.
var bodyParser = require('body-parser');
//Object of Express
const app = express();
app.use(express.static('views'));
app.use(bodyParser.urlencoded({ extended: true }));
//Node Session and cookies
var cookieParser = require('cookie-parser');
var session = require('express-session');
// initialize cookie-parser to allow us access the cookies stored in the browser.
app.use(cookieParser());
// initialize express-session to allow us track the logged-in user across sessions.
app.use(session({
key: 'user_sid',
secret: 'ss',
resave: false,
saveUninitialized: false,
cookie: {
expires: 7*24*3600*1000
}
}));
//URL Of MongoDB Server.
const url = process.env.MongoURL;
//Mongo Client Variable
const MongoClient = require('mongodb').MongoClient;
//Database Name.
const dbName = process.env.dbName;
// This middleware will check if user's cookie is still saved in browser and user is not set, then automatically log the user out.
// This usually happens when you stop your express server after login, your cookie still remains saved in the browser.
app.use((req, res, next) => {
if (req.cookies.user_sid && !req.session.user) {
res.clearCookie('user_sid');
}
next();
});
// middleware function to check for logged-in users
var sessionChecker = (req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
res.redirect('/Dashboard');
} else {
next();
}
};
// middleware function to check for logged-in users
var LoginChecker = (req, res, next) => {
if (req.session.user && req.cookies.user_sid) {
console.log("User Signed IN :- "+req.session.user.email);
next();
} else {
res.redirect('/');
}
};
//Replace with your Own Google Client ID For Sign In Perpose.
var CLIENT_ID = process.env.clientID;
//to verifythe login (using google's own function to verify)
const {OAuth2Client} = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify(token,req,res) {
var response="";
var user={};
try
{
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
user.userid = payload['sub'];
//console.log(payload);
response="success";
user.email=payload['email'];
user.name=payload['name'];
user.picture=payload['picture'];
}
catch(e)
{
//error
console.log("error"+e);
response="error";
}
finally
{
//console.log(response);
if(response=="success")
{
//Setting the Session
req.session.user=user;
res.send("success");
}
else
{
res.send("error");
}
}
}
app.get('/',sessionChecker, (req, res) => {
res.render('home');
});
// route for user logout
app.get('/logout', (req, res) => {
if (req.session.user && req.cookies.user_sid) {
res.clearCookie('user_sid');
res.redirect('/');
} else {
res.redirect('/');
}
});
//404 Page
app.get('/404', (req, res) => {
res.render('404');
});
//Terms And Conditions Page
app.get('/Terms', (req, res) => {
res.render('Terms');
});
//Privacy Page
app.get('/Privacy', (req, res) => {
res.render('Privacy');
});
//API Page
app.get('/API', (req, res) => {
res.render('API');
});
//Edit Short URL
app.post('/Edit',LoginChecker, (req, res) => {
//console.log(req.body.token);
var id=ObjectId(req.body.token);
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.find({ _id : id , owner : req.session.user.email}).toArray(function(err,docs)
{
//console.log(docs);
if(docs.length==1)
{
res.render('Edit',{data:docs});
}
else
{
//Else Home.
res.redirect('/');
}
});
client.close();
});
});
//Edit URL Next Step
app.post('/EditURL',LoginChecker, (req, res) => {
//console.log(req.body.token);
var shorturl=req.body.short;
shorturl=shorturl.replace(/[^a-zA-Z0-9 ]/g, "");
shorturl=shorturl.replace(" ","");
var longurl=req.body.long;
var id=ObjectId(req.body.token);
//Checking if Custom URl is available or not
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.find({ linkkey : shorturl }).toArray(function(err,docs)
{
//console.log(docs);
if(docs.length==0)
{
EditURLStep3(res,req,longurl,shorturl,id);
}
else if(docs.length==1)
{
if(docs[0]._id==req.body.token)
{
EditURLStep3(res,req,longurl,shorturl,id);
}
else
{
res.send("Ahhh! This Custom URL is already Occupied :(");
}
}
else
{
res.send("Ahhh! This Custom URL is already Occupied :(");
}
});
client.close();
});
});
//Step 3 Towards EditURL
function EditURLStep3(res,req,longurl,shorturl,id)
{
if(CheckURL(longurl))
{
if(longurl.includes("tinyfor.me"))
{
res.send("This URL is not allowed.");
}
else
{
//Updating the DATA.
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.updateOne(
{_id: id, owner : req.session.user.email},
{$set:{
url: longurl,
linkkey: shorturl
}}
, function(err, result){
if(err) res.send("Something Went Wrong");
res.redirect("/Dashboard");
});
});
}
}
else
{
res.send("Please Enter a vaild URL.");
}
}
//Delete URL
app.post('/DeleteURL',LoginChecker, (req, res) => {
//console.log(req.body.token);
var id=ObjectId(req.body.token);
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.removeOne(
{_id: id, owner : req.session.user.email}
, function(err, result){
if(err) res.send("Something Went Wrong");
res.redirect("/Dashboard");
});
});
});
//Dashboard
app.get('/Dashboard',LoginChecker, (req, res) => {
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('users');
collection.find({ Email : req.session.user.email }).toArray(function(err,docs)
{
//console.log(docs);
//for New User
if(docs.length==0)
{
insertData(req,res);
}
else
{
//Registered User
GetHistory(req,res);
}
});
client.close();
});
});
//Verify the google login
app.post('/verifylogin', (req, res) => {
verify(req.body.token,req, res);
});
app.post('/UpdateStatus',LoginChecker, (req, res) => {
var id=ObjectId(req.body.token);
var status=req.body.status;
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.updateOne(
{_id: id, owner : req.session.user.email},
{$set:{
status:status
}}
, function(err, result){
if(err) res.send("Something Went Wrong");
res.redirect("/Dashboard");
});
});
});
//Short URL (Signed in user)
app.post('/shorturl',LoginChecker, (req, res) => {
var longurl=req.body.longurl;
var shorturl=req.body.shorturl;
shorturl=shorturl.replace(/[^a-zA-Z0-9 ]/g, "");
shorturl=shorturl.replace(" ","");
//If no Custom URL is Given / Random URl generation
if(shorturl==undefined || shorturl==null || shorturl=="" || shorturl==" " || shorturl=='')
{
var newshort=shorturl;
if(shorturl==undefined || shorturl==null || shorturl=="" || shorturl==" " || shorturl=='')
{
console.log("Generating Random URL...");
var t=2;
var temp=getrandom(t);
while(CheckAvailability(temp)==0)
{
//Increasing the size of Random URL
temp=getrandom(t++);
}
newshort=temp;
}
//To check wheather URL is vaild or not.
IsVaildURL(longurl,newshort,req,res);
}
else
{
//Checking if Custom URl is available or not
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.find({ linkkey : shorturl }).toArray(function(err,docs)
{
//console.log(docs);
if(docs.length==0)
{
//URL Vaildaiton
IsVaildURL(longurl,shorturl,req,res);
}
else
{
res.send("Ahhh! This Custom URL is already Occupied :(");
}
});
client.close();
});
}
});
function IsVaildURL(longurl,shorturl,req,res)
{
if(CheckURL(longurl))
{
if(longurl.includes("tinyfor.me"))
{
res.send("This URL is not allowed.");
}
else
{
//Main Step to enter the data in DB.
ShortURL(longurl,shorturl,req,res);
}
}
else
{
res.send("Please Enter a vaild URL.");
}
}
function ShortURL(longurl,shorturl,req,res)
{
//Just Entering the Data in DB.
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.insertOne(
{
linkkey: shorturl,
url:longurl,
owner:req.session.user.email,
DateOfCreation:new Date().toLocaleString(),
status:'on',
count:"0"
},function(data,err)
{
res.send('https://tinyfor.me/'+shorturl);
});
client.close();
});
}
//Checking Random URL is Available or not.
function CheckAvailability(temp)
{
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.find({ linkkey : temp }).toArray(function(err,docs)
{
console.log(docs);
if(docs.length==0)
{
return 1;
}
else
{
return 0;
}
});
client.close();
});
}
//Getting Short URLs History
function GetHistory(req,res)
{
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.find({ owner : req.session.user.email }).toArray(function(err,docs)
{
res.render('dashboard',{data:req.session.user,history:docs});
});
client.close();
});
}
//inserting New User Data
function insertData(req,res)
{
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('users');
collection.insertOne(
{
Name: req.session.user.name,
Email:req.session.user.email,
Profile:req.session.user.picture,
UserId:req.session.user.userid,
DateOfCreation:new Date().toLocaleString()
},function(data,err)
{
GetHistory(req,res);
});
client.close();
});
}
//Public API for Short URL almost same as Private without having Custom URL Support
app.post('/api/shorturl', (req, res) => {
var longurl=req.body.longurl;
var newshort="";
console.log("Generating Random URL...");
var t=2;
var temp=getrandom(t);
while(CheckAvailability(temp)==0)
{
temp=getrandom(t++);
}
newshort=temp;
if(CheckURL(longurl))
{
if(longurl.includes("tinyfor.me"))
{
res.send("This URL is not allowed.");
}
else
{
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
collection.insertOne(
{
linkkey: newshort,
url:longurl,
DateOfCreation:new Date().toLocaleString(),
status:'on',
count:"0"
},function(data,err)
{
res.send('https://tinyfor.me/'+newshort);
});
client.close();
});
}
}
else
{
res.send("Please Enter a vaild URL.");
}
});
//Redirecting to the Main URL
app.get('/:id', (req, res) => {
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
var id=req.params.id;
collection.find({ linkkey : id , status : 'on'}).toArray(function(err,docs)
{
//console.log(docs);
if(docs.length==1)
{
//Maintaining the Count.
UpdateCount(res,req,docs[0].linkkey,docs[0].url,docs[0].count);
}
else
{
//Else 404.
res.redirect('/404');
}
});
client.close();
});
});
//Random URl Generation
function getrandom(no){
var random_string = Math.random().toString(32).substring(2, no) + Math.random().toString(32).substring(2, 5);
//console.log(random_string);
return random_string;
}
//Using Regular Exprssion to checking the string is url or not.
function CheckURL(str)
{
//Regular Expression to Check Wheather URL is Vaild or not !
var expression = /https?:[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
var t = str;
if (t.match(regex)) {
return true;
} else {
return false;
}
}
//When User Opens the links, to maintain the count of oppening of the url
function UpdateCount(res,req,shorturl,murl,count)
{
MongoClient.connect(url,{ useNewUrlParser: true },function(err,client){
const db = client.db(dbName);
const collection = db.collection('links');
var newcount=1 + parseInt(count, 10);
collection.updateOne({ linkkey : shorturl }, {$set : {count : newcount}},function(err,docs)
{
if(err)
{
res.redirect('/404');
}
else
{
res.redirect(murl);
}
});
client.close();
});
}
//Httpserver Port Number 3000.
app.listen(process.env.PORT || 3000, function(){
console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});
//Set The File Type To App As EJS.
app.set('view engine', 'ejs');