-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
577 lines (473 loc) · 13.5 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
// Imports--
const express = require("express");
const clc = require("cli-color");
const { Model } = require("mongoose");
const mongoose = require("mongoose");
const bcrypt = require("bcrypt");
const validator = require("validator");
const session = require("express-session");
const mongoDbSession = require("connect-mongodb-session")(session);
const jwt = require("jsonwebtoken");
// File imports--
const {
cleanUpAndValidate,
generateJWTToken,
sendVerificationToken,
SECRET_KEY,
} = require("./utils/AuthUtils");
const userSchema = require("./userSchema");
const bookSchema = require("./models/libraryModel");
const { isAuth } = require("./middleWares/AuthMiddleWare");
const { rateLimiting } = require("./middleWares/rateLimiting");
// Variables--
const app = express();
const PORT = process.env.PORT || 8080; // after deploying the port which is freely available will be automatically assigned!!
const MONGODB_URI = `mongodb+srv://prashantmishramark43:[email protected]/Library-Management`;
// ejs(view engine) // it will search the files inside the view
// folder then it will render You don't have to import anything
app.set("view engine", "ejs");
app.use(express.static("public"));
// db connection
mongoose
.connect(MONGODB_URI)
.then(() => {
console.log(clc.green.bold.underline("MongoDb connected"));
})
.catch((err) => {
console.log(clc.red.bold(err));
});
// middleware's
//remember we have to use middleware because by default the data is url-encoded format so we need to type cast into the json formate
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
const store = new mongoDbSession({
uri: MONGODB_URI,
collection: "sessions",
});
app.use(
session({
secret: "Library Management application ",
resave: false,
saveUninitialized: false,
store: store,
})
);
// Routes(Note- urls are not case sensitive they will be converted to smaller case)--
app.get("/", (req, res) => {
return res.render("login");
});
app.get("/registration", (req, res) => {
return res.render("Signup");
});
app.get("/login", (req, res) => {
return res.render("login");
});
app.get("/resetpassword", (req, res) => {
return res.render("resetpassword");
});
app.get("/newpassword", (req, res) => {
return res.render("newpassword");
});
// end point for signup and login page to post the data to the server!!
//remember we have to use middleware because by default the data is url-encoded format so we need to type cast into the json formate
//
//MVC
// Model- functions which interact with database
// utility functions- functions which does not interact with db
app.post("/registration", async (req, res) => {
console.log(req.body, "-----");
const { name, email, password, username, phone } = req.body;
try {
await cleanUpAndValidate({ name, email, password, username, phone });
// console.log(data, "data after hitting api");
//check if the user exits
const userExistEmail = await userSchema.findOne({ email });
console.log(userExistEmail);
if (userExistEmail) {
return res.send({
status: 400,
message: "Email Already exits",
});
}
const userExistUsername = await userSchema.findOne({ username });
if (userExistUsername) {
return res.send({
status: 400,
message: "Username Already exits",
});
}
//hash the password using bcypt
let saltRound = 10;
const hashPassword = await bcrypt.hash(password, saltRound);
const user = new userSchema({
name: name,
email: email,
password: hashPassword,
username: username,
phone: phone,
emailAuthenticated: false,
resetPassword: false,
});
const verificationToken = generateJWTToken(email);
// console.log(verificationToken);
try {
const userDb = await user.save();
sendVerificationToken(email, verificationToken);
console.log(userDb);
return res.send({
status: 200,
message: "Please verify your email before login",
});
} catch (error) {
console.log(error);
return res.send({
status: 401,
message: "Data Base error",
error: error,
});
}
} catch (error) {
return res.send({
status: 401,
error: error,
});
}
});
app.get("/verify/:token", async (req, res) => {
console.log(req.params, "inside verify");
const token = req.params.token;
jwt.verify(token, SECRET_KEY, async (err, decodedData) => {
if (err) throw err;
try {
const usercheckDb = await userSchema.findOne({
email: decodedData.email,
});
if (usercheckDb.resetPassword) {
return res.status(200).redirect("/newpassword");
} else {
const userDb = await userSchema.findOneAndUpdate(
{ email: decodedData.email },
{ emailAuthenticated: true }
);
console.log(userDb);
return res.status(200).redirect("/login");
}
} catch (error) {
return res.send({
status: 400,
message: "Invalid Authentication Link",
error: error,
});
}
});
});
app.post("/login", async (req, res) => {
//validate the data
// console.log(req.body, "login successful");
const { loginId, password } = req.body;
if (!loginId || !password) {
return res.send({
status: 400,
message: "missing credentials",
});
}
if (typeof loginId !== "string" || typeof password !== "string") {
return res.send({
status: 400,
message: "Invalid data format",
});
}
//identify the loginId and search in database
try {
let userDb;
if (validator.isEmail(loginId)) {
userDb = await userSchema.findOne({ email: loginId });
} else {
userDb = await userSchema.findOne({ username: loginId });
}
// console.log(userDb, "login userDb successful");
if (!userDb) {
return res.send({
status: 400,
message: "User not found, Please register first",
});
}
console.log(userDb);
if (!userDb.emailAuthenticated) {
return res.send({
status: 400,
message: "Please verify your email before login",
});
}
//password compare bcrypt.compare
const isMatch = await bcrypt.compare(password, userDb.password);
if (!isMatch) {
return res.send({
status: 400,
message: "Password Does not match",
});
}
//Add session base auth sys
req.session.isAuth = true;
req.session.user = {
username: userDb.username,
email: userDb.email,
userId: userDb._id,
};
return res.redirect("/dashboard");
} catch (error) {
console.log(error);
return res.send({
status: 500,
message: "Database error",
error: error,
});
}
});
app.post("/reset", async (req, res) => {
console.log(req.body);
const { loginId } = req.body;
console.log(loginId, "reset email");
try {
const userExistEmail = await userSchema.findOne({ email: loginId });
console.log(userExistEmail, "email from find one");
if (!userExistEmail) {
return res.send({
status: 400,
message: "Email not found in database, please register",
});
}
const userDb = await userSchema.findOneAndUpdate(
{ email: loginId },
{ resetPassword: true }
);
const verificationToken = generateJWTToken(loginId);
console.log(verificationToken, "verification token");
sendVerificationToken(loginId, verificationToken);
return res.send({
status: 200,
message: "Please verify your email and for resetting the password ",
});
// return res.status(200).redirect("/newpassword");
} catch (error) {
return res.send({
status: 400,
message: "Invalid email ",
error: error,
});
}
});
app.post("/updatepassword", async (req, res) => {
const { password, loginId } = req.body;
try {
let saltRound = 10;
const hashPassword = await bcrypt.hash(password, saltRound);
const userDb = await userSchema.findOneAndUpdate(
{ email: loginId },
{ password: hashPassword, resetPassword: false }
// { "$set": { "name": name, "genre": genre, "author": author, "similar": similar}}
);
return res.status(200).redirect("/login");
} catch (error) {
return res.send({
status: 500,
message: "something went wrong.. ",
error: error,
});
}
});
app.get("/dashboard", isAuth, async (req, res) => {
return res.render("dashboard");
});
app.get("/profile", isAuth, async (req, res) => {
return res.render("profile");
});
//logout api's
app.post("/logout", isAuth, (req, res) => {
console.log(req.session);
req.session.destroy((err) => {
if (err) throw err;
return res.redirect("/login");
});
});
app.post("/logout_from_all_devices", isAuth, async (req, res) => {
const username = req.session.user.username;
//create a session schema
const Schema = mongoose.Schema;
const sessionSchema = new Schema({ _id: String }, { strict: false });
const sessionModel = mongoose.model("session", sessionSchema);
try {
const deletionCount = await sessionModel.deleteMany({
"session.user.username": username,
});
console.log(deletionCount);
return res.send({
status: 200,
message: "Logout from all devices successfully",
});
} catch (error) {
return res.send({
status: 500,
message: "Logout Failed",
error: error,
});
}
});
//post books
app.post("/create-item", isAuth, async (req, res) => {
console.log(req.session.user.username, "server has got an req");
const { title, author, price, category } = req.body.book;
//intialize todo schema and store it in Db
// res.send("saved book: " + bookDB);
try {
const Book = new bookSchema({
title: title,
author: author,
price: price,
category: category,
username: req.session.user.username,
});
const bookDB = await Book.save();
console.log(bookDB, " data saved");
return res.send({
status: 201,
message: "book added successfully",
data: bookDB,
});
} catch (error) {
console.log(error, "Error saving");
return res.send({
status: 500,
message: "Database error",
error: error,
});
}
});
app.get("/read-item", async (req, res) => {
// console.log(req.session.user.username, "read item");
const user_name = req.session.user.username;
try {
const book = await bookSchema.find({ username: user_name });
// console.log(book, "sssssssssss")
if (book.length === 0)
return res.send({
status: 200,
message: "Library is empty, Please add some books.",
});
return res.send({
status: 200,
message: "Read Success",
data: book,
});
} catch (error) {
return res.send({
status: 500,
message: "Database error",
error: error,
});
}
});
app.get("/read-profile", async (req, res) => {
const email = req.session.user.email;
// console.log(userDb, "ssssssss profile of user")
try {
user = await userSchema.findOne({ email: email });
if (!user)
return res.send({
status: 200,
message: "no user found.",
});
return res.send({
status: 200,
message: "Read Success",
data: user,
});
} catch (error) {
return res.send({
status: 500,
message: "Database error",
error: error,
});
}
});
app.post("/edit-item", isAuth, async (req, res) => {
// console.log(req.body);
let { id, field, newData } = req.body;
field = field.toLowerCase();
if (field === "price" && newData === null) {
return res.send({
status: 400,
message: "Invalid input format",
});
}
if (!id || !newData || !field) {
return res.send({
status: 400,
message: "Missing credentials",
});
}
try {
const bookDB = await bookSchema.findOneAndUpdate(
{ _id: id },
{ [field]: newData }
);
let temp = { ...bookDB, [field]: newData };
return res.send({
status: 200,
message: "books updated Successfully",
data: temp,
});
} catch (error) {
console.log(error, "error from backend");
return res.send({
status: 500,
message: "Database error",
error: error,
});
}
});
app.post("/delete-item", isAuth, async (req, res) => {
console.log(req.body, "delete api hit");
const id = req.body.id;
//data validation
if (!id) {
return res.send({
status: 400,
message: "Missing credentials",
});
}
try {
const bookDB = await bookSchema.findOneAndDelete({ _id: id });
console.log(bookDB);
return res.send({
status: 200,
message: "Book deleted Successfully",
data: bookDB,
});
} catch (error) {
return res.send({
status: 500,
message: "Database error",
error: error,
});
}
});
app.listen(PORT, () => {
console.log(
clc.underline.italic.magentaBright(`Hello, world! Port No- ${PORT}`)
);
console.log(clc.underline.italic.redBright(`http://localhost:${PORT}`));
});
//EGS
// step1 create server and connect to mongodb database!.
// Step2 SignUP( 1.data validation/cleanup, 2.first check user exits or not
// if not then create a user in db,)
// Step3 Email verification ...
// Step4 login
// after login redirect to dashboard!.
// command-
// initialize node JS- npm init -y
// install express and nodemon- npm i express nodemon mongoose
// using package for CLI Colors-- https://www.npmjs.com/package/cli-color
//To start the server - npm run dev