-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
656 lines (530 loc) · 21.7 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
var express = require("express");
var app = express();
var formidable = require("express-formidable");
app.use(formidable());
var mongodb = require("mongodb");
var mongoClient = mongodb.MongoClient;
var ObjectId = mongodb.ObjectId;
var httpObj = require("http");
var http = httpObj.createServer(app);
var bcrypt = require("bcrypt");
var fileSystem = require("fs");
var session = require("express-session");
require("dotenv").config();
app.use(session({
secret: process.env.SECRET_KEY,
resave: false,
saveUninitialized: false
}));
app.use(express.static("public"));
// app.use("/public/css", express.static(__dirname + "/public/css"));
// app.use("/public/js", express.static(__dirname + "/public/js"));
// app.use("/public/img", express.static(__dirname + "/public/img"));
// app.use("/public/font-awesome-4.7.0", express.static(__dirname + "/public/font-awesome-4.7.0"));
// app.use("/public/fonts", express.static(__dirname + "/public/fonts"));
app.set("view engine", "ejs");
var mainURL = "http://localhost:3000";
var database = null;
// app middleware to attach main URL and user object with each request
app.use(function (request, result, next) {
// Dynamically determine the base URL from the incoming request
request.mainURL = request.protocol + '://' + request.get('host');
request.isLogin = (typeof request.session.user !== "undefined");
request.user = request.session.user;
next();
});
// recursive function to get the file from uploaded
function recursiveGetFile (files, _id) {
var singleFile = null;
for (var a = 0; a < files.length; a++) {
const file = files[a];
// return if file type is not folder and ID is found
if (file.type != "folder") {
if (file._id == _id) {
return file;
}
}
// if it is a folder and have files, then do the recursion
if (file.type == "folder" && file.files.length > 0) {
singleFile = recursiveGetFile(file.files, _id);
// return the file if found in sub-folders
if (singleFile != null) {
return singleFile;
}
}
}
}
// function to add new uploaded object and return the updated array
function getUpdatedArray (arr, _id, uploadedObj) {
for (var a = 0; a < arr.length; a++) {
// push in files array if type is folder and ID is found
if (arr[a].type == "folder") {
if (arr[a]._id == _id) {
arr[a].files.push(uploadedObj);
arr[a]._id = ObjectId(arr[a]._id);
}
// if it has files, then do the recursion
if (arr[a].files.length > 0) {
arr[a]._id = ObjectId(arr[a]._id);
getUpdatedArray(arr[a].files, _id, uploadedObj);
}
}
}
return arr;
}
// recursive function to remove the file and return the updated array
function removeFileReturnUpdated(arr, _id) {
for (var a = 0; a < arr.length; a++) {
if (arr[a].type != "folder" && arr[a]._id == _id) {
// remove the file from uploads folder
try {
fileSystem.unlinkSync(arr[a].filePath);
} catch (exp) {
//
}
// remove the file from array
arr.splice(a, 1);
break;
}
// do the recursion if it has sub-folders
if (arr[a].type == "folder" && arr[a].files.length > 0) {
arr[a]._id = ObjectId(arr[a]._id);
removeFileReturnUpdated(arr[a].files, _id);
}
}
return arr;
}
// recursive function to search uploaded files
function recursiveSearch (files, query) {
var singleFile = null;
for (var a = 0; a < files.length; a++) {
const file = files[a];
if (file.type == "folder") {
// search folder case-insensitive
if (file.folderName.toLowerCase().search(query.toLowerCase()) > -1) {
return file;
}
if (file.files.length > 0) {
singleFile = recursiveSearch(file.files, query);
if (singleFile != null) {
// need parent folder in case of files
if (singleFile.type != "folder") {
singleFile.parent = file;
}
return singleFile;
}
}
} else {
if (file.name.toLowerCase().search(query.toLowerCase()) > -1) {
return file;
}
}
}
}
// recursive function to search shared files
function recursiveSearchShared (files, query) {
var singleFile = null;
for (var a = 0; a < files.length; a++) {
var file = (typeof files[a].file === "undefined") ? files[a] : files[a].file;
if (file.type == "folder") {
if (file.folderName.toLowerCase().search(query.toLowerCase()) > -1) {
return file;
}
if (file.files.length > 0) {
singleFile = recursiveSearchShared(file.files, query);
if (singleFile != null) {
if (singleFile.type != "folder") {
singleFile.parent = file;
}
return singleFile;
}
}
} else {
if (file.name.toLowerCase().search(query.toLowerCase()) > -1) {
return file;
}
}
}
}
// start the http server
http.listen(process.env.PORT, function () {
console.log("Server started at " + "port: " + process.env.PORT );
// connect with mongo DB server
mongoClient.connect(process.env.MONGO_URI, {
useUnifiedTopology: true
}, function (error, client) {
// connect database (it will automatically create the database if not exists)
database = client.db("SkyVault");
console.log("Database connected.");
// app.get("/Admin", async function (request, result) {
// // render an HTML page with number of pages, and posts data
// result.render("Admin", {
// request: request
// });
// });
// search files or folders
app.get("/Search", async function (request, result) {
const search = request.query.search;
if (request.session.user) {
var user = await database.collection("users").findOne({
"_id": ObjectId(request.session.user._id)
});
var fileUploaded = await recursiveSearch(user.uploaded, search);
var fileShared = await recursiveSearchShared(user.sharedWithMe, search);
// check if file is uploaded or shared with user
if (fileUploaded == null && fileShared == null) {
request.status = "error";
request.message = "File/folder '" + search + "' is neither uploaded nor shared with you.";
result.render("Search", {
"request": request
});
return false;
}
var file = (fileUploaded == null) ? fileShared : fileUploaded;
file.isShared = (fileUploaded == null);
result.render("Search", {
"request": request,
"file": file
});
return false;
}
result.redirect("/Login");
});
app.post("/DeleteLink", async function (request, result) {
const _id = request.fields._id;
if (request.session.user) {
var link = await database.collection("public_links").findOne({
$and: [{
"uploadedBy._id": ObjectId(request.session.user._id)
}, {
"_id": ObjectId(_id)
}]
});
if (link == null) {
request.session.status = "error";
request.session.message = "Link does not exists.";
const backURL = request.header("Referer") || "/";
result.redirect(backURL);
return false;
}
await database.collection("public_links").deleteOne({
$and: [{
"uploadedBy._id": ObjectId(request.session.user._id)
}, {
"_id": ObjectId(_id)
}]
});
request.session.status = "success";
request.session.message = "Link has been deleted.";
const backURL = request.header("Referer") || "/";
result.redirect(backURL);
return false;
}
result.redirect("/Login");
});
app.get("/MySharedLinks", async function (request, result) {
if (request.session.user) {
var links = await database.collection("public_links").find({
"uploadedBy._id": ObjectId(request.session.user._id)
}).toArray();
result.render("MySharedLinks", {
"request": request,
"links": links
});
return false;
}
result.redirect("/Login");
});
app.get("/SharedViaLink/:hash", async function (request, result) {
const hash = request.params.hash;
var link = await database.collection("public_links").findOne({
"hash": hash
});
if (link == null) {
request.session.status = "error";
request.session.message = "Link expired.";
result.render("SharedViaLink", {
"request": request
});
return false;
}
result.render("SharedViaLink", {
"request": request,
"link": link
});
});
app.post("/ShareViaLink", async function (request, result) {
const _id = request.fields._id;
if (request.session.user) {
var user = await database.collection("users").findOne({
"_id": ObjectId(request.session.user._id)
});
var file = await recursiveGetFile(user.uploaded, _id);
if (file == null) {
request.session.status = "error";
request.session.message = "File does not exists";
const backURL = request.header("Referer") || "/";
result.redirect(backURL);
return false;
}
bcrypt.hash(file.name, 10, async function (error, hash) {
hash = hash.substring(10, 20);
const link = mainURL + "/SharedViaLink/" + hash;
await database.collection("public_links").insertOne({
"hash": hash,
"file": file,
"uploadedBy": {
"_id": user._id,
"name": user.name,
"email": user.email
},
"createdAt": new Date().getTime()
});
request.session.status = "success";
request.session.message = "Share link: " + link;
const backURL = request.header("Referer") || "/";
result.redirect(backURL);
});
return false;
}
result.redirect("/Login");
});
// delete uploaded file
app.post("/DeleteFile", async function (request, result) {
const _id = request.fields._id;
if (request.session.user) {
var user = await database.collection("users").findOne({
"_id": ObjectId(request.session.user._id)
});
var updatedArray = await removeFileReturnUpdated(user.uploaded, _id);
for (var a = 0; a < updatedArray.length; a++) {
updatedArray[a]._id = ObjectId(updatedArray[a]._id);
}
await database.collection("users").updateOne({
"_id": ObjectId(request.session.user._id)
}, {
$set: {
"uploaded": updatedArray
}
});
const backURL = request.header('Referer') || '/';
result.redirect(backURL);
return false;
}
result.redirect("/Login");
});
// download file
app.post("/DownloadFile", async function (request, result) {
const _id = request.fields._id;
var link = await database.collection("public_links").findOne({
"file._id": ObjectId(_id)
});
if (link != null) {
fileSystem.readFile(link.file.filePath, function (error, data) {
// console.log(error);
result.json({
"status": "success",
"message": "Data has been fetched.",
"arrayBuffer": data,
"fileType": link.file.type,
// "file": mainURL + "/" + file.filePath,
"fileName": link.file.name
});
});
return false;
}
if (request.session.user) {
var user = await database.collection("users").findOne({
"_id": ObjectId(request.session.user._id)
});
var fileUploaded = await recursiveGetFile(user.uploaded, _id);
if (fileUploaded == null) {
result.json({
"status": "error",
"message": "File is neither uploaded nor shared with you."
});
return false;
}
var file = fileUploaded;
fileSystem.readFile(file.filePath, function (error, data) {
// console.log(error);
result.json({
"status": "success",
"message": "Data has been fetched.",
"arrayBuffer": data,
"fileType": file.type,
// "file": mainURL + "/" + file.filePath,
"fileName": file.name
});
});
return false;
}
result.json({
"status": "error",
"message": "Please login to perform this action."
});
return false;
});
// view all files uploaded by logged-in user
app.get("/MyUploads", async function (request, result) {
if (request.session.user) {
var user = await database.collection("users").findOne({
"_id": ObjectId(request.session.user._id)
});
var uploaded = user.uploaded;
result.render("MyUploads", {
"request": request,
"uploaded": uploaded
});
return false;
}
result.redirect("/Login");
});
// upload new file
app.post("/UploadFile", async function (request, result) {
if (request.session.user) {
var user = await database.collection("users").findOne({
"_id": ObjectId(request.session.user._id)
});
if (request.files.file.size > 0) {
const _id = request.fields._id;
var uploadedObj = {
"_id": ObjectId(),
"size": request.files.file.size, // in bytes
"name": request.files.file.name,
"type": request.files.file.type,
"filePath": "",
"createdAt": new Date().getTime()
};
var filePath = "./uploads" + user.email + "/" + new Date().getTime() + "-" + request.files.file.name;
uploadedObj.filePath = filePath;
if (!fileSystem.existsSync("./uploads/" + user.email)){
fileSystem.mkdirSync("./uploads/" + user.email);
}
// Read the file
fileSystem.readFile(request.files.file.path, function (err, data) {
if (err) throw err;
console.log('File read!');
// Write the file
fileSystem.writeFile(filePath, data, async function (err) {
if (err) throw err;
console.log('File written!');
await database.collection("users").updateOne({
"_id": ObjectId(request.session.user._id)
}, {
$push: {
"uploaded": uploadedObj
}
});
request.session.status = "success";
request.session.message = "Image has been uploaded. Try our premium version for image compression.";
result.redirect("/MyUploads/" + _id);
});
// Delete the file
fileSystem.unlink(request.files.file.path, function (err) {
if (err) throw err;
console.log('File deleted!');
});
});
} else {
request.status = "error";
request.message = "Please select valid image.";
result.render("MyUploads", {
"request": request
});
}
return false;
}
result.redirect("/Login");
});
// logout the user
app.get("/Logout", function (request, result) {
request.session.destroy();
result.redirect("/");
});
// show page to login
app.get("/Login", function (request, result) {
result.render("Login", {
"request": request
});
});
// authenticate the user
app.post("/Login", async function (request, result) {
var email = request.fields.email;
var password = request.fields.password;
var user = await database.collection("users").findOne({
"email": email
});
if (user == null) {
request.status = "error";
request.message = "Email does not exist.";
result.render("Login", {
"request": request
});
return false;
}
bcrypt.compare(password, user.password, function (error, isVerify) {
if (isVerify) {
request.session.user = user;
result.redirect("/");
return false;
}
request.status = "error";
request.message = "Password is not correct.";
result.render("Login", {
"request": request
});
});
});
// register the user
app.post("/Register", async function (request, result) {
var name = request.fields.name;
var email = request.fields.email;
var password = request.fields.password;
var reset_token = "";
var isVerified = true;
var verification_token = new Date().getTime();
var user = await database.collection("users").findOne({
"email": email
});
if (user == null) {
bcrypt.hash(password, 10, async function (error, hash) {
await database.collection("users").insertOne({
"name": name,
"email": email,
"password": hash,
"reset_token": reset_token,
"uploaded": [],
"sharedWithMe": [],
"isVerified": isVerified,
"verification_token": verification_token
}, async function (error, data) {
request.status = "success";
request.message = "Signed up successfully. You can login now.";
result.render("Register", {
"request": request
});
});
});
} else {
request.status = "error";
request.message = "Email already exist.";
result.render("Register", {
"request": request
});
}
});
// show page to do the registration
app.get("/Register", function (request, result) {
result.render("Register", {
"request": request
});
});
// home page
app.get("/", function (request, result) {
result.render("index", {
"request": request
});
});
});
});