-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
441 lines (372 loc) · 10.5 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
import express from "express";
import bcrypt from "bcrypt";
import { initializeApp } from "firebase/app";
import {
getFirestore,
doc,
collection,
setDoc,
getDoc,
updateDoc,
getDocs,
query,
where,
deleteDoc,
limit,
} from "firebase/firestore";
import stripe from "stripe";
// Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDFAF2XJkhQI6RhC6wzDjmckv7bkR5ncxE",
authDomain: "online-ecommerce-website.firebaseapp.com",
projectId: "online-ecommerce-website",
storageBucket: "online-ecommerce-website.appspot.com",
messagingSenderId: "480575089097",
appId: "1:480575089097:web:72c353d4cf6d8d82952018",
};
// Initialize Firebase
const firebase = initializeApp(firebaseConfig);
const db = getFirestore();
// Init server
const app = express();
// Middlewares - to make public folder to static folder
app.use(express.static("public"));
// Enable form sharing
app.use(express.json());
// AWS
import aws from "aws-sdk";
import "dotenv/config";
// AWS setup
const region = "ap-south-1";
const bucketName = "furnituredotcom";
const accessKeyId = process.env.AWS_ACCESS_KEY;
const secretAccessKey = process.env.AWS_SECRET_KEY;
aws.config.update({
region,
accessKeyId,
secretAccessKey,
});
// Init s3
const s3 = new aws.S3();
// Generate image url
async function generateURL() {
let date = new Date();
const imageName = `${date.getTime()}.jpeg`;
const params = {
Bucket: bucketName,
Key: imageName,
Expires: 300,
ContentType: "image/jpeg",
};
const uploadURL = await s3.getSignedUrlPromise("putObject", params);
return uploadURL;
}
app.get("/s3url", (req, res) => {
generateURL().then((url) => res.json(url));
});
// Routes
// Home route
app.get("/", (req, res) => {
res.sendFile("index.html", { root: "public" });
});
// Signup route
app.get("/signup", (req, res) => {
res.sendFile("signup.html", { root: "public" });
});
app.post("/signup", (req, res) => {
const { name, email, password, number, tac } = req.body;
// Form validations
if (name.length < 5) {
res.json({ alert: "Name must be at least 5 characters long." });
} else if (!email.length) {
res.json({ alert: "Please enter a valid email." });
} else if (password.length < 8) {
res.json({ alert: "Password must be at least 8 characters long." });
} else if (!/^\d{10}$/.test(number)) {
res.json({ alert: "Please enter a valid 10-digit mobile number." });
} else if (!tac) {
res.json({ alert: "Please agree to our terms and conditions." });
} else {
// Store the data in db
const users = collection(db, "users");
getDoc(doc(users, email)).then((user) => {
if (user.exists()) {
return res.json({
alert: "Email already exists, please use different email to signup.",
});
} else {
// Encrypt the password
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(password, salt, (err, hash) => {
req.body.password = hash;
req.body.seller = false;
// Set the doc
setDoc(doc(users, email), req.body).then((data) => {
res.json({
name: req.body.name,
email: req.body.email,
seller: req.body.seller,
});
});
});
});
}
});
}
});
// Login route
app.get("/login", (req, res) => {
res.sendFile("login.html", { root: "public" });
});
app.post("/login", (req, res) => {
let { email, password } = req.body;
if (!email.length || !password.length) {
return res.json({ alert: "fill all the inputs" });
}
const users = collection(db, "users");
getDoc(doc(users, email)).then((user) => {
if (!user.exists()) {
return res.json({ alert: "email does not exists" });
} else {
bcrypt.compare(password, user.data().password, (err, result) => {
if (result) {
let data = user.data();
return res.json({
name: data.name,
email: data.email,
seller: data.seller,
});
} else {
return res.json({ alert: "password is incorrect" });
}
});
}
});
});
// Seller route
app.get("/seller", (req, res) => {
res.sendFile("seller.html", { root: "public" });
});
app.post("/seller", (req, res) => {
let { name, address, about, number, email } = req.body;
if (
!name.length ||
!address.length ||
!about.length ||
number.length < 10 ||
!Number(number)
) {
return res.json({ alert: "some information(s) is/are incorrect" });
} else {
// Update the seller status
const sellers = collection(db, "sellers");
setDoc(doc(sellers, email), req.body).then((data) => {
const users = collection(db, "users");
updateDoc(doc(users, email), {
seller: true,
}).then((data) => {
res.json({ seller: true });
});
});
}
});
// Dashboard route
app.get("/dashboard", (req, res) => {
res.sendFile("dashboard.html", { root: "public" });
});
// Add product route
app.get("/add-product", (req, res) => {
res.sendFile("add-product.html", { root: "public" });
});
// Edit product route
app.get("/add-product/:id", (req, res) => {
res.sendFile("add-product.html", { root: "public" });
});
app.post("/add-product", (req, res) => {
let { name, shortDes, detail, price, image, tags, email, draft, id } =
req.body;
if (!draft) {
if (!name.length) {
res.json({ alert: "should enter product name" });
} else if (!shortDes.length) {
res.json({ alert: "short des must be 80 letters long" });
} else if (!price.length || !Number(price)) {
res.json({ alert: "enter valid price" });
} else if (!detail.length) {
res.json({ alert: "must enter the detail" });
} else if (!tags.length) {
res.json({ alert: "enter tags" });
}
}
let docName =
id == undefined
? `${name.toLowerCase()}-${Math.floor(Math.random() * 50000)}`
: id;
let products = collection(db, "products");
setDoc(doc(products, docName), req.body)
.then((data) => {
res.json({ product: name });
})
.catch((err) => {
res.json({ alert: "some error occured." });
});
});
app.post("/get-products", (req, res) => {
let { email, id, tag } = req.body;
let products = collection(db, "products");
let docRef;
if (id) {
docRef = getDoc(doc(products, id));
} else if (tag) {
docRef = getDocs(query(products, where("tags", "array-contains", tag)));
} else {
docRef = getDocs(query(products, where("email", "==", email)));
}
docRef.then((products) => {
if (products.empty) {
return res.json("no products");
}
let productArr = [];
if (id) {
return res.json(products.data());
} else {
products.forEach((item) => {
let data = item.data();
data.id = item.id;
productArr.push(data);
});
}
res.json(productArr);
});
});
// Delete route
app.post("/delete-product", (req, res) => {
let { id } = req.body;
deleteDoc(doc(collection(db, "products"), id))
.then((data) => {
res.json("success");
})
.catch((err) => {
res.json("error");
});
});
// Product page route by id
app.get("/products/:id", (req, res) => {
res.sendFile("product.html", { root: "public" });
});
// Serach route
app.get("/search/:key", (req, res) => {
res.sendFile("search.html", { root: "public" });
});
// Review route
app.post("/add-review", (req, res) => {
let { headline, review, rate, email, product } = req.body;
// Form validations
if (
!headline.length ||
!review.length ||
rate == 0 ||
email == null ||
!product
) {
return res.json({ alert: "Fill all the inputs" });
}
// Storing in Firestore
let reviews = collection(db, "reviews");
let docName = `review-${email}-${product}`;
setDoc(doc(reviews, docName), req.body)
.then((data) => {
return res.json("review");
})
.catch((err) => {
res.json({ alert: "some err occurred" });
});
});
app.post("/get-reviews", (req, res) => {
let { product, email } = req.body;
let reviews = collection(db, "reviews");
getDocs(query(reviews, where("product", "==", product)), limit(4)).then(
(review) => {
let reviewArr = [];
if (review.empty) {
return res.json(reviewArr);
}
let userEmail = false;
review.forEach((item, i) => {
let reivewEmail = item.data().email;
if (reivewEmail == email) {
userEmail = true;
}
reviewArr.push(item.data());
});
if (!userEmail) {
getDoc(doc(reviews, `review-${email}-${product}`)).then((data) =>
reviewArr.push(data.data())
);
}
return res.json(reviewArr);
}
);
});
// Cart route
app.get("/cart", (req, res) => {
res.sendFile("cart.html", { root: "public" });
});
// Checkout route
app.get("/checkout", (req, res) => {
res.sendFile("checkout.html", { root: "public" });
});
// Stripe payment
let stripeGateway = stripe(process.env.stripe_key);
let DOMAIN = process.env.DOMAIN;
app.post("/stripe-checkout", async (req, res) => {
const session = await stripeGateway.checkout.sessions.create({
payment_method_types: ["card"],
mode: "payment",
success_url: `${DOMAIN}/success?session_id={CHECKOUT_SESSION_ID}&order=${JSON.stringify(
req.body
)}`,
cancel_url: `${DOMAIN}/checkout?payment_fail=true`,
line_items: req.body.items.map((item) => {
return {
price_data: {
currency: "inr",
product_data: {
name: item.name,
description: item.shortDes,
images: [item.image],
},
unit_amount: item.price * 100,
},
quantity: item.item,
};
}),
});
res.json(session.url);
});
// Payment success route
app.get("/success", async (req, res) => {
let { order, session_id } = req.query;
try {
const session = await stripeGateway.checkout.sessions.retrieve(session_id);
const customer = await stripeGateway.customers.retrieve(session.customer);
let date = new Date();
let order_collection = collection(db, "orders");
let docName = `${customer.email}-order-${date.getTime()}`;
setDoc(doc(order_collection, docName), JSON.parse(order)).then((date) => {
res.redirect("/checkout?payment=done");
});
} catch {
res.redirect("/404");
}
});
// 404 route
app.get("/404", (req, res) => {
res.sendFile("404.html", { root: "public" });
});
app.use((req, res) => {
res.redirect("/404");
});
app.listen(3000, () => {
console.log("listening on port 3000");
});