-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
623 lines (525 loc) · 19.1 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
require("dotenv").config();
// to restrict the usage on production phase of project
const express=require('express');
const app=express();
const mongoose =require('mongoose');
const Product=require("./models/products.js");
const User=require("./models/user.js");
const Order=require("./models/orders.js");
const wrapAsync=require("./utils/WrapAsync.js");
const expressError=require("./utils/ExpressError.js");
const {listingSchema}=require("./Schema.js");
const path=require("path");
const ejsMate =require("ejs-mate");
const methodOverride =require("method-override");
const bodyParser = require('body-parser');
const ExpressError = require('./utils/ExpressError.js');
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const nodemailer = require('nodemailer');
const multer = require('multer');
const {storage}=require("./cloudConfig.js");
const upload=multer({storage});
const jwt = require('jsonwebtoken');
const cookieparser=require('cookie-parser');
const { decode } = require('punycode');
const WrapAsync = require('./utils/WrapAsync.js');
const Razorpay = require('razorpay');
const port=process.env.PORT
app.use(express.json());
app.set("views","ejs");
app.set("views",path.join(__dirname,"views"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.urlencoded({extended:true}));
app.engine("ejs",ejsMate);
app.use(express.static(path.join(__dirname,"public")));
app.use('/uploads', express.static(path.join(__dirname, 'uploads')));
app.use(methodOverride("_method"));
app.use(cookieparser())
const MONGO_URL=process.env.MONGO_URL;
function generateToken(User) {
return jwt.sign({ id: User._id ,role:User.role},process.env.JWT_SECRET );
}
async function getUser(cookies){
const token=cookies?.uid;
const decoded= jwt.verify(token, process.env.JWT_SECRET);
const reqUser=await User.findById(decoded.id);
return reqUser;
}
main()
.then(()=>{
console.log("db connected");
})
.catch(err=>{
console.log(err)
});
async function main(){
await mongoose.connect(MONGO_URL);
}
app.get('/reca',wrapAsync((req, res) => {
res.render("welcome/welcome.ejs",{});
}));
app.get("/reca/signin",wrapAsync((req,res)=>{
res.render("welcome/signin.ejs",{message:null});
}));
app.get("/reca/signup",wrapAsync(async (req,res)=>{
res.render("welcome/signup.ejs",{message:null});
}));
const validatePhoneNumber = (phoneNumber) => {
// Validate phone number format (10 digits)
return /^\d{10}$/.test(phoneNumber);
};
const validateRollNumber = (rollNumber) => {
// Validate roll number format (11 characters, first two > 19)
if (rollNumber.length !== 10) return false;
const firstTwoDigits = rollNumber.substring(0, 2);
return /^\d+$/.test(firstTwoDigits) && parseInt(firstTwoDigits) > 19;
const sixthCharacter=rollNumber.charAt(5);
return /^[AMP]$/.test(sixthCharacter);
};
const validatePassword=(password)=>{
};
app.post("/reca/signup", async (req, res) => {
let { name, email, rollno, phono, password } = req.body;
if (!validateRollNumber(rollno)) {
return res.status(400).render('welcome/signup.ejs', { message: 'Invalid roll number' });
}
// Validate phone number
if (!validatePhoneNumber(phono)) {
return res.status(400).render('welcome/signup.ejs', { message: 'Invalid phone number' });
}
// Validate roll number
// If validations pass, proceed with hashing password and saving user
try {
const salt = await bcrypt.genSalt(10);
const newPassword = await bcrypt.hash(password, salt);
let newuser = new User({
name: `${name}`,
email: `${email}`,
phono: `${phono}`,
rollno: `${rollno}`,
password: `${newPassword}`,
role: 'NORMAL',
otp: null,
otpExpiration: null,
});
await newuser.save(); // Use await to properly handle asynchronous operations
res.redirect("/reca/signin");
} catch (err) {
res.status(500).send(err.message);
}
});
app.post("/reca/signin",wrapAsync(async (req, res) => {
const { rollno, password } = req.body;
try {
const user = await User.findOne({ rollno: `${rollno}` });
if (!user) {
return res.render('welcome/signin.ejs',{message:'Invalid user'});
}
const isValid=await bcrypt.compare(password,user.password)
if (!isValid) {
return res.status(400).render('welcome/signin.ejs',{message:'Invalid password'});
}
const token = generateToken(user);
res.cookie('uid',token);
res.render("user/home.ejs", {user});
} catch (err) {
res.status(500).send(err.message);
}
}));
app.get("/reca/home",wrapAsync(async(req,res)=> {
let user=await getUser(req.cookies);
res.render("user/home.ejs",{user});
}));
app.get("/reca/forgotpassword",wrapAsync((req,res)=>{
res.render("welcome/forgotpassword.ejs",{});
}));
app.post('/reca/send-otp',wrapAsync( async (req, res) => {
const { rollno, phono} = req.body;
const user = await User.findOne({ rollno, phono });
if (!user) {
return res.status(404).send('User not found');
}
let transporter=nodemailer.createTransport({
service:'gmail',
auth:{
user:'[email protected]',
pass:'bltx xiex ajet qydb'
}
});
// Generate OTP
const otp = crypto.randomBytes(3).toString('hex');
user.otp = otp;
user.otpExpiration = Date.now() + 3600000; // OTP valid for 1 hour
await user.save();
// Send OTP via email using NodeMailer
const mail_configs = {
from: '[email protected]',
to: user.email,
subject: 'Your OTP Code',
text: `Your OTP code is ${otp}`
};
transporter.sendMail(mail_configs,function(error,info){
if(error){
console.error(error)
return reject({message:'error occured'})
}
return resolve({message:'succesful'})
});
}));
// Endpoint to reset password
app.post('/reca/reset-password',wrapAsync( async (req, res) => {
const { otp, newPassword } = req.body;
const user = await User.findOne({ otp, otpExpiration: { $gt: Date.now() } });
if (!user) {
return res.status(400).send('Invalid OTP or OTP has expired');
}
// Hash the new password and save
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(newPassword, salt);
user.otp = undefined;
user.otpExpiration = undefined;
await user.save();
res.redirect("/reca/signin.ejs");
}));
app.get("/reca/products",wrapAsync(async (req,res)=>{
const allListings=await Product.find({});
res.render("listings/index.ejs",{allListings});
}));
app.get("/reca/new",wrapAsync((req,res)=>{
console.log("new page");
res.render("listings/new.ejs",{});
}));
app.get("/reca/aboutus",(req,res)=>{
res.render('about_us.ejs');
});
app.get("/reca/mycart",wrapAsync(async (req, res) => {
try{
const reqUser=await getUser(req.cookies);
const user= await reqUser.populate("cart");
let cartItems=user.cart;
console.log(cartItems);
let totalAmount = cartItems.reduce((total, item) => {
return total + (item.price ); // assuming item.price and item.quantity
}, 0);
res.render('user/mycart.ejs', { cartItems ,totalAmount});
} catch (error) {
console.error('Error rendering cart:', error);
res.status(500).send('Internal Server Error');
}
}));
app.get("/reca/user", wrapAsync(async (req, res) => {
try {
const reqUser=await getUser(req.cookies)
const user = await reqUser.populate([{
path: "products",
model: "Product",
}, {
path: "orders",
model: "Order",
populate: {
path: "products", // populate the products in each order
model: "Product"
}
}]);
if (!user) {
return res.status(404).send('User not found');
}
const orderedItems = user.orders.map(order => order.products).flat();
const soldItems = user.products;
console.log(orderedItems);
res.render('user/userprofile.ejs', { user, orderedItems, soldItems });
} catch (error) {
console.error('Error rendering user orders:', error);
res.status(500).send('Internal Server Error');
}
}));
// sell route
app.post('/addproduct',upload.single('image'), wrapAsync(async (req, res, next) => {
if (!req.body.listing) {
throw new ExpressError(400, 'Send valid product details');
}
const { title, description, price, branch, category } = req.body.listing;
const image = req.file.path; // Assuming Multer gives a unique filename
console.log(image);
const newProduct = new Product({
title,
description,
price,
branch,
category,
image: image, // Save path to the image
});
let userproduct=await newProduct.save();
let user=await getUser(req.cookies);
user.products.push(userproduct);
user.save();
res.redirect('/reca/products');
}));
app.post('/cart/add', WrapAsync(async (req, res,next) => {
console.log("add");
const token = req.cookies?.uid;
if (!token) {
return res.status(401).send("Unauthorized: No token provided");
}
try{
const decoded = jwt.verify(token,process.env.JWT_SECRET);
const userId = decoded.id; // Assuming you have user authentication and `req.user` contains the logged-in user's info
const { productId } = req.body;
let user = await User.findById(userId);
if (user) {
const cartProduct = user.cart.find(id => id.toString() === productId);
console.log(cartProduct);
if (!cartProduct) {
user.cart.push(productId);
await user.save();
res.redirect("/reca/products");
} else {
res.status(400).send("Item is already in the cart!");
throw new ExpressError(404,"page not found");
}
} else {
res.status(404).send("User not found");
}
}
catch(err){
next(err);
}
}));
app.post('/reca/cart/remove',wrapAsync(async(req,res)=>{
const productId = req.body.productId;
const reqUser=await getUser(req.cookies);
let user =await reqUser.populate('cart');
user.cart.remove(productId);
user.save();
let cartItems=user.cart;
res.redirect("/reca/mycart");
}));
//payment
const razorpay = new Razorpay({
key_id: 'rzp_live_1j2EriedZMsgq4',
key_secret: 'h1WUmj019fY4ld1UDCDPgWjE',
});
//create order
app.post('/create-order', wrapAsync(async (req, res) => {
const { amount, currency, receipt } = req.body;
const options = {
amount: amount * 100, // amount in the smallest currency unit
currency,
receipt,
};
try {
const order = razorpay.orders.create(options,function(err,order){
res.json(order);
});
} catch (error) {
res.status(500).send('Error creating Razorpay order');
}
}));
const { ObjectId } = mongoose.Types;
const jwtSecret = process.env.JWT_SECRET; // Replace with your actual secret key
app.post('/verify-payment', wrapAsync(async (req, res) => {
console.log("verify is received");
const { order_id, payment_id, signature, userId } = req.body;
console.log(order_id, payment_id, signature, userId);
try {
const decodedToken = jwt.verify(userId, jwtSecret);
const userIdFromToken = decodedToken.id;
const generatedSignature = crypto.createHmac('sha256', 'h1WUmj019fY4ld1UDCDPgWjE')
.update(`${order_id}|${payment_id}`)
.digest('hex');
if (generatedSignature === signature) {
// Payment verification successful
const user = await User.findById(userIdFromToken).populate('cart');
console.log(user);
if (!user) {
return res.status(404).json({ success: false, message: 'User not found' });
}
const newOrder = new Order({
user: user._id,
products: user.cart,
totalAmount: user.cart.reduce((total, item) => total + item.price, 0),
paymentId: payment_id,
status: 'pending',
});
await newOrder.save();
user.orders.push(newOrder._id);
const cartProductUpdates = user.cart.map(async (item) => {
const product = await Product.findById(item._id);
console.log(product);
if (product) {
product.available = false;
await product.save();
}
});
await Promise.all(cartProductUpdates);
user.cart = [];
await user.save();
res.json({ success: true, message: 'Payment verified and order created' });
} else {
res.status(400).json({ success: false, message: 'Payment verification failed' });
}
} catch (err) {
console.error(err);
res.status(500).json({ success: false, error: err.message });
}
}));
app.get('/reca/admin', restrictTo(['ADMIN']), wrapAsync(async (req, res) => {
const users = await User.find({});
const products = await Product.find({});
const orders = await Order.find({ status: "pending" })
.populate('user')
.populate('products');
const ordersdelivered = await Order.find({ status: "delivered" });
// Fetching sellers for each product in the orders
const ordersWithSellers = await Promise.all(orders.map(async order => {
const productsWithSellers = await Promise.all(order.products.map(async product => {
const seller = await User.findOne({ products: product._id });
return { product, seller };
}));
return { ...order.toObject(), products: productsWithSellers,ordersdelivered };
}));
res.render('admin/admin.ejs', { users, products, orders: ordersWithSellers,ordersdelivered });
}));
app.delete("/admin/products/remove/:id", restrictTo(['ADMIN']), wrapAsync(async (req, res) => {
let { id } = req.params;
// Delete the product by ID
await Product.findByIdAndDelete(id);
// Find all users who have this product in their products array
await User.updateMany(
{ products: id }, // Find users with the product ID in their products array
{ $pull: { products: id } } // Remove the product ID from the array
);
res.redirect("/reca/admin");
}));
app.post('/admin/orders/deliver/:id', restrictTo(['ADMIN']), wrapAsync(async (req, res) => {
try {
await Order.findByIdAndUpdate(req.params.id, { status: 'Delivered' });
res.json({ success: true });
} catch (err) {
res.json({ success: false, error: err });
}
}));
app.get('/admin/orders/cancel/:id', restrictTo(['ADMIN']), wrapAsync(async (req, res) => {
try {
const orderId = req.params.id;
// Find the order by ID
const order = await Order.findById(orderId);
if (!order) {
return res.json({ success: false, error: 'Order not found' });
}
// Remove the order ID from the user's orders array
const user = await User.findByIdAndUpdate(order.user, {
$pull: { orders: orderId }
}, { new: true });
// Update the availability of each product in the order
await Promise.all(order.products.map(async (productId) => {
await Product.findByIdAndUpdate(productId, {
available: true
});
}));
// Remove the order from the Order schema
const deletedOrder = await Order.findByIdAndDelete(orderId);
if (!deletedOrder) {
console.error(`Failed to delete order: ${orderId}`);
return res.json({ success: false, error: 'Failed to delete order' });
}
// Add an alert to the user
user.alerts.push(`Your order with ID ${orderId} has been cancelled.`);
await user.save();
res.json({ success: true });
} catch (err) {
res.json({ success: false, error: err.message });
}
}));
//edit route
app.get("/listings/:id/edit",wrapAsync(async (req,res)=>{
let {id}=req.params;
console.log(id);
const listing= await Product.findById(id);
res.render("listings/edit.ejs",{listing});
}));
//edit for admin
app.get("/admin/listings/:id/edit",restrictTo(['ADMIN']),wrapAsync(async (req,res)=>{
console.log("update received");
let {id}=req.params;
console.log(id);
const listing= await Product.findById(id);
res.render("admin/edit.ejs",{listing});
}));
//update route
app.put("/listings/:id",wrapAsync(async (req,res)=>{
let {id}=req.params;
let listing=req.body.listing;
await Product.findByIdAndUpdate(id,{...req.body.listing});
res.redirect(`/listings/${id}`);
}));
//admin update
app.put("/admin/listings/:id",wrapAsync(async (req,res)=>{
let {id}=req.params;
let listing=req.body.listing;
await Product.findByIdAndUpdate(id,{...req.body.listing});
res.redirect(`/reca/admin`);
}));
app.put("/listings/:id",wrapAsync(async (req,res)=>{
let {id}=req.params;
let listing=req.body.listing;
await Product.findByIdAndUpdate(id,{...req.body.listing});
res.redirect(`/listings/${id}`);
}));
//delete route
app.delete("/listings/:id", wrapAsync(async (req,res)=>{
let {id}=req.params;
await Product.findByIdAndDelete(id);
res.redirect("/reca/user");
}));
// reca products
app.get("/reca/products/:branch/:category", wrapAsync(async (req, res) => {
const { branch, category } = req.params;
let allListings = await Product.find({ branch, category });
res.render("listings/index.ejs", { allListings });
}));
app.get("/reca/products",wrapAsync(async(req,res)=>{
let allListings=await Product.find({});
res.render("listings/index.ejs",{allListings});
}));
app.get("/listings/:id",wrapAsync(async (req,res)=>{
let {id}=req.params;
const listing= await Product.findById(id);
res.render("listings/show.ejs",{listing});
}));
//admin page route
app.get('/reca/adminpage',restrictTo(['ADMIN']),wrapAsync((req,res)=>{
// countUsers().then((count)=>noOfUsers=count)
// console.log(noOfUsers)
res.render('admin/admin.ejs');
}));
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(err.status || 500);
//res.render('error.ejs', { message: err.message });
res.send("Error Occured");
});
//counting number of users
async function countUsers() {
try {
const count = await User.countDocuments({});
return count;
} catch (err) {
return err
}
}
countUsers();
// Call the function
function restrictTo(roles=[]){
return function(req,res,next){
const token=req.cookies?.uid;
const decoded= jwt.verify(token,process.env.JWT_SECRET);
if(!roles.includes(decoded.role))
return res.end('Unauthorized')
return next();
}
}
app.listen(port,()=>{
console.log("Server is On");
});