-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
226 lines (195 loc) · 5.72 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
const express = require("express");
const { executeQuery } = require("./database");
const path = require("path");
const ejs = require("ejs");
const { clear } = require("console");
const app = express();
const PORT = process.env.PORT || 4000;
let isAuthenticated = false;
let userID = -1;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
console.log(__dirname);
app.set("view engine", "ejs");
app.set("views", path.join(__dirname, "views"));
const isAuthenticatedMiddleware = (req, res, next) => {
if (isAuthenticated) {
next(); // Continue to the next middleware or route handler
} else {
res.redirect("/login"); // Redirect to login if not authenticated
}
};
// Apply the isAuthenticatedMiddleware to all routes except "/login" and "/signup"
app.use((req, res, next) => {
if (req.path === "/login" || req.path === "/signup") {
next(); // Allow access to login and signup routes without authentication
} else {
isAuthenticatedMiddleware(req, res, next); // Apply isAuthenticatedMiddleware to other routes
}
});
/*
Routes
*/
app.get("/home", (req, res) => {
res.render("index");
});
app.get("/", (req, res) => {
res.render("login");
});
app.get("/order", async (req, res) => {
const user = await executeQuery(`
SELECT * FROM users WHERE user_id = ${userID};
`);
const userAddress = await executeQuery(`
SELECT * FROM addresses WHERE user_id = 23;
`);
const orderItems = await executeQuery(`
SELECT c.order_id, c.user_id, c.product_id AS cart_product_id, c.quantity,
p.product_id AS product_id, p.coffee_name, p.coffee_type,
p.origin, p.price, p.roasting_level, p.aroma, p.description
FROM orders c
INNER JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ${userID};
`);
res.render("orders", { orderItems, user, userAddress });
});
app.get("/login", (req, res) => {
res.render("login");
});
app.get("/signup", (req, res) => {
res.render("signup");
});
app.get("/cart", async (req, res) => {
try {
console.log(userID);
const cartItems = await executeQuery(`
SELECT c.cart_id, c.user_id, c.product_id AS cart_product_id, c.quantity,
p.product_id AS product_id, p.coffee_name, p.coffee_type,
p.origin, p.price, p.roasting_level, p.aroma, p.description
FROM cart c
INNER JOIN products p ON c.product_id = p.product_id
WHERE c.user_id = ${userID};
`);
let totalBill = 0;
cartItems.forEach((item) => {
totalBill += item.quantity * item.price;
});
console.log("Total Bill:", totalBill);
console.log(cartItems);
res.render("cart", { cartItems, totalBill }); // Pass cartItems to the cart EJS template
} catch (err) {
console.error(err);
res.status(500).send("Error fetching cart items.");
}
});
app.get("/featured", async (req, res) => {
const products = await executeQuery("select * from products");
res.render("featuredProducts", { products }); // Pass cartItems to the cart EJS template
});
app.get("/recent", (req, res) => {
res.render("recentlyLaunched");
});
app.get("/thanks", async (req, res) => {
const clearOrders = await executeQuery(
`DELETE FROM orders where user_id = ${userID}`
);
const orderId = Math.floor(Math.random() * 1000000);
const cartItems = await executeQuery(`
SELECT c.product_id , c.quantity from cart c where user_id = ${userID};
`);
for (let i = 0; i < cartItems.length; i++) {
const createOrder = await executeQuery(`
INSERT INTO orders (order_id, user_id, product_id, quantity) VALUES ('${orderId}', ${userID}, ${cartItems[i].product_id}, ${cartItems[i].quantity});
`);
}
const clearCart = await executeQuery(
`DELETE FROM cart where user_id = ${userID}`
);
res.render("thanks");
});
app.get('/new', (req, res) => {
res.render('new');
});
/**
*
*
*
*
*
* DB LOGIC
*
*
*
*/
app.post("/signup", async (req, res) => {
const { username, fname, lname, email, pass ,phone } = req.body;
const sql =
"INSERT INTO users (username, first_name, last_name, email, password,phone_number) VALUES ('" +
username +
"', '" +
fname +
"', '" +
lname +
"', '" +
email +
"', '" +
pass +
"', '" +
phone +
"')";
try {
const result = await executeQuery(sql);
res.redirect("/login");
} catch (error) {
res.status(500).send("Error creating user");
}
});
app.post("/login", async (req, res) => {
const { email, pass } = req.body;
const sql =
"SELECT * FROM users WHERE email = '" +
email +
"' AND password = '" +
pass +
"'";
try {
const result = await executeQuery(sql);
if (result.length > 0) {
userID = result[0].user_id;
isAuthenticated = true;
console.log(result);
res.redirect("/home");
} else {
res.redirect("/login");
}
} catch (error) {
res.status(500).send("Error logging in");
}
});
app.post("/removeFromCart", async (req, res) => {
const cartId = req.body.itemId;
const removeItem = await executeQuery(`
DELETE FROM cart where cart_id = ${cartId};
`);
res.sendStatus(200);
});
app.post("/addToCart", async (req, res) => {
const productId = req.body.productId;
const cartItem = await executeQuery(`
SELECT * FROM cart WHERE user_id = ${userID} AND product_id = ${productId};
`);
if (cartItem.length > 0) {
const updateItem = await executeQuery(`
UPDATE cart SET quantity = quantity + 1 WHERE user_id = ${userID} AND product_id = ${productId};
`);
} else {
const addItem = await executeQuery(`
INSERT INTO cart (user_id, product_id, quantity) VALUES (${userID}, ${productId}, 1);
`);
}
res.sendStatus(200);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});