-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
321 lines (290 loc) · 9.42 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
const os = require("os");
const cluster = require("cluster");
const total_cpu = os.availableParallelism();
// console.log(total);
if (cluster.isPrimary) {
for (let i = 0; i < total_cpu; i++) {
cluster.fork();
}
} else {
const express = require("express");
const app = express();
// const { v4: uuidv4 } = require("uuid");
const mongoose = require("mongoose");
const path = require("path");
const PORT = process.env.PORT || 5000;
const bodyParser = require("body-parser");
const Product = require("./models/productSchema");
const User = require("./models/userSchema");
const Suggestion = require("./models/suggestionSchema");
const multer = require("multer");
const { protect } = require("./middleware/auth");
const jwt = require("jsonwebtoken");
require("dotenv").config();
const cookieParser = require("cookie-parser");
const cloudinary = require("./utils/cloudinary");
const session = require("express-session");
const flush = require("connect-flash");
const Rent = require("./models/rentSchema");
mongoose.connect(process.env.MONGO_URI).then(() => {
console.log("MONGODB CONNECTED");
});
// console.log(`The Id is: ${process.pid}`);
const array = [];
// MiddleWares
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 60000,
},
})
);
app.use(flush());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, "public")));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "uploads")));
// console.log(__dirname);
// View Engine
app.set("view engine", "ejs");
app.set("views", path.resolve("./views"));
// Multer Setup
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "uploads");
},
filename: function (req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname));
},
});
const upload = multer(
{ storage: storage },
{ limits: { fileSize: 5 * 1024 * 1024 } }
);
// upload and create a new item
app.post("/upload", upload.single("productImage"), async (req, res) => {
const { Name, Price, Contact_NO, ADDRESS, category, rent } = req.body;
try {
const result = await cloudinary.uploader.upload(req.file.path, {
folder: "uploads",
});
const newItem = new Product({
Name,
Price,
Contact_NO,
ADDRESS,
productImage: {
public_id: result.public_id,
url: result.secure_url,
},
category,
rent,
});
await newItem.save();
console.log("New item added:", newItem);
res.status(201).json("File uploaded successfully.");
} catch (error) {
console.error("Error adding new item:", error);
res.status(500).send("Error adding new item");
}
});
app.get("/about_section", (req, res) => {
const token = req.cookies.token;
return res.render("about", { cookie: token });
});
app.get("/", (req, res) => {
// console.log("Cookies:", req.cookies.token); // Log cookies to the console
const token = req.cookies.token; // Retrieve the cookie
res.render("index", { cookie: token }); // Pass the cookie to the template
});
app.get("/api/user/", async (req, res) => {
try {
const products = await Product.find({}).sort({ createdAt: -1 });
const token = req.cookies.token;
// Render the 'show' EJS template and pass the products array to it
return res.render("show", {
products: products,
cloud_name: process.env.cloud_name,
cookie: token,
});
} catch (error) {
console.error("Error fetching products:", error);
res.status(500).send("Error fetching products");
}
});
app.post("/button", (req, res) => {
res.render("home");
});
app.post("/signup/user", async (req, res) => {
const { name, email, password } = req.body;
// console.log(req.body);
try {
const newUser = await User.create({
name,
email,
password,
});
// console.log("New User added:", newUser);
const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET_KEY, {
expiresIn: process.env.JWT_EXPIRY,
});
res.cookie("token", token, {
httpOnly: true,
secure: false,
maxAge: 3600000,
});
console.log(req.cookies.token);
req.flash("msg", "Successfully signed");
res.redirect("/");
// Render the signup page
} catch (error) {
console.error("Error adding new user:", error);
req.flash("msg", " Something Went Wrong");
res.status(500).send("Error adding new user");
}
});
app.post("/submitsuggestion", async (req, res) => {
const { suggestion } = req.body;
try {
const newSuggestion = await Suggestion.create({
suggestion,
});
res.status(200).render("thanks");
} catch (error) {
console.error("Error adding new suggestion:", error);
res.status(500).send("Error adding new suggestion");
}
});
app.get("/getOne/:id", async (req, res) => {
try {
const { id } = req.params;
const product = await Product.findById(id);
if (!product) {
// Product with the given ID not found
return res.status(404).send("Product not found");
}
const token = req.cookies.token;
res.render("details", { product: product, cookie: token });
} catch (error) {
// Handle any errors that occur during the execution
console.error("Error fetching product:", error);
res.status(500).send("Error fetching product");
}
});
app.get("/rent-form/:id", async (req, res) => {
const id = req.params.id;
const item = await Product.findById(id);
const token = req.cookies.token;
return res.render("rent", { item: item, cookie: token });
});
// app.get("/rent/:id", async (req, res) => {
// const id = req.params.id;
// const item = await Product.findById(id);
// res.render("rent", { item: item });
// });
app.post("/rent-post/:id", async (req, res) => {
const { Name, email, day, role } = req.body;
const id = req.params.id;
const product = await Product.findById(id);
// console.log(product);
const rentItem = await Rent.create({ Name, email, day, role });
res
.status(200)
.render("payment2", { product: product, rentItem: rentItem });
});
app.get("/logout", async (req, res) => {
res.clearCookie("token");
// res.redirect("/login");
res.status(200).json("Logout Successfully");
});
app.get("/login", (req, res) => {
const token = req.cookies.token;
res.render("login", { cookie: token });
});
app.post("/login", async (req, res) => {
const { email, password } = req.body;
const user = await User.findOne({ email }).select("+password");
console.log(user);
if (!user || !user.correctPassword(password, user.password)) {
return res.status(401).send("Invalid email or password");
}
res.status(200).send("User login successfully");
});
//Add To Cart
app.get("/addtocart/:id", async (req, res) => {
const { id } = req.params;
const token = req.cookies.token;
try {
const product = await Product.findById(id);
if (product) {
array.push(product);
res.render("cart", { array: array, cookie: token });
} else {
// Product not found
res.status(404).send("Product not found");
}
} catch (error) {
// Error occurred while fetching product
console.error("Error fetching product:", error);
res.status(500).send("Internal Server Error");
}
});
//DeleteRequest for Product
app.delete("/remove/:id", async (req, res) => {
const { id } = req.params;
try {
const deletedUser = await User.findByIdAndDelete(id);
res.send(deletedUser);
} catch (error) {
console.error("Error deleting user:", error);
res.status(500).send("Error deleting user");
}
});
app.get("/allProducts", async (req, res) => {
const products = await Product.find({});
const token = req.cookies.token;
return res.render("show", { products: products, cookie: token });
});
app.get("/explore", async (req, res) => {
const products = await Product.find({});
const token = req.cookies.token;
return res.render("show", { products: products, cookie: token });
});
app.get("/signup/get", (req, res) => {
res.render("signup");
});
app.get("/home", (req, res) => {
// const token = req.cookies.token;
// res.render("index", { user: req.user, cookie: token });
res.redirect("/");
});
app.get("/suggest", (req, res) => {
const token = req.cookies.token;
return res.render("suggestion", { cookie: token });
});
app.get("/user", async (req, res) => {
const token = req.cookies.token;
if (!token) {
res.status(500).json("Token Not Found");
}
const decoded = jwt.verify(token, process.env.JWT_SECRET_KEY);
if (!decoded) {
res.status(500).json("No decoded found");
}
// console.log(decoded.id);
const user = await User.findById(decoded.id);
// console.log(user);
res.render("profile1", { user: user });
});
app.get("/add", (req, res) => {
const token = req.cookies.token;
res.render("add", { cookie: token });
});
app.listen(PORT, () => {
console.log(`App is running at http://localhost:${PORT}`);
});
}