forked from cs4241-22a/final_project
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.js
More file actions
494 lines (469 loc) · 18 KB
/
server.js
File metadata and controls
494 lines (469 loc) · 18 KB
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
require('dotenv').config()
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const bcrypt = require('bcrypt');
const { MongoClient, ServerApiVersion, ObjectId } = require('mongodb');
const helmet = require('helmet');
const uuidv4 = require('uuid').v4;
const cookieParser = require('cookie-parser');
const saltRounds = 10;
const itemTypes = {
CANNEDJARRED: "Canned / Jarred Goods", // "canned-jarred"
DAIRY: "Dairy", // "dairy"
DRYBAKING: "Dry / Baking Goods", // "dry-baking"
FROZEN: "Frozen", // "frozen"
GRAINS: "Grains", // "grains"
MEAT: "Meat", // "meat"
PRODUCE: "Produce", // "produce"
OTHER: "Other", // "other"
}
const uri = 'mongodb+srv://goGrocery:onCTPMLKBjCDBp40@cluster0.ptctsas.mongodb.net/?retryWrites=true&w=majority';
const client = new MongoClient(uri, {useNewUrlParser: true, useUnifiedTopology: true,});
let collection = null;
// Init express application
const app = express();
const sessions = new Map();
// Start listening on defined port
app.listen(process.env.PORT || 3000, () => {
console.log('Now listening on port ' + process.env.PORT || 3000);
});
// Middleware setup
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
app.use(helmet({
crossOriginEmbedderPolicy: false
}));
// Get routes
app.get("/cart-data", (req, resp) => {
// Fetch user data from DB
const sessionId = req.cookies.session.substring(1);
const userId = sessions.get(sessionId);
if (!userId) {
resp.status(401);
resp.end();
} else {
console.log("Session valid. getting user data")
client.connect((err, client) => {
if (err) {
throw err;
} else {
// If DB connection is successful
const db = client.db("database");
const cartCode = req.query["cart"];
console.log("Fetching cart: " + cartCode);
db.collection("carts").findOne({"code": cartCode}, {}, (err, res) => {
if (err) {
throw err;
} else {
if (!res || !res.cannedJarredData) {
resp.status(404);
resp.end();
} else {
// Found user document
const body = {
cannedJarredData: res.cannedJarredData,
dairyData: res.dairyData,
dryBakingData: res.dryBakingData,
frozenData: res.frozenData,
grainsData: res.grainsData,
meatData: res.meatData,
produceData: res.produceData,
otherData: res.otherData
}
resp.json(JSON.stringify(body));
resp.status(200);
resp.end();
}
}
})
}
})
}
})
app.get("/home-cart", (req, resp) => {
// Fetch user data from DB
const sessionId = req.cookies.session.substring(1);
const userId = sessions.get(sessionId);
if (!userId) {
resp.status(401);
resp.end();
} else {
console.log("Session valid. getting user data")
client.connect((err, client) => {
if (err) {
throw err;
} else {
// If DB connection is successful
const db = client.db("database");
const cartCode = req.query["cart"];
console.log("Fetching cart: " + cartCode);
db.collection("users").findOne({"_id": userId}, {}, (err, res) => {
if (err) {
throw err;
} else {
if (!res) {
resp.status(404);
resp.end();
} else {
// Found user document
const body = {
homeCart: res.homeCart
}
resp.json(JSON.stringify(body));
resp.status(200);
resp.end();
}
}
})
}
})
}
})
app.post("/add-item", (req, resp) => {
const data = req.body;
if (!data) { // Guard clause
resp.end();
}
const sessionId = req.cookies.session.substring(1);
const userId = sessions.get(sessionId);
if (!userId) {
resp.status(401);
resp.end();
} else {
console.log("Session valid. Adding item")
client.connect((err, client) => {
if (err) {
throw err;
} else {
// If DB connection is successful
const db = client.db("database");
db.collection("carts").findOne({"code": data.cartCode}, {}, (err, res) => {
if (err) {
throw err;
} else {
// Found user document
// Edit correct field
let array = null;
let field = null;
switch(data.itemType) {
case itemTypes.CANNEDJARRED:
array = res.cannedJarredData;
field = "cannedJarredData";
break;
case itemTypes.DAIRY:
array = res.dairyData;
field = "dairyData";
break;
case itemTypes.DRYBAKING:
array = res.dryBakingData;
field = "dryBakingData";
break;
case itemTypes.FROZEN:
array = res.frozenData;
field = "frozenData";
break;
case itemTypes.GRAINS:
array = res.grainsData;
field = "grainsData";
break;
case itemTypes.MEAT:
array = res.meatData;
field = "meatData";
break;
case itemTypes.PRODUCE:
array = res.produceData;
field = "produceData";
break;
case itemTypes.OTHER:
array = res.otherData;
field = "otherData";
break;
default:
array = null;
field = null;
break;
}
if (!array) {
resp.end();
}
console.log("Array valid");
array.push(data.itemName);
db.collection("carts").updateOne({"code": data.cartCode}, { $set: {[field]: array} }, (err, result) => {
console.log(result);
if (err) {
throw err;
} else {
resp.status(200);
resp.end();
}
});
}
})
}
})
}
})
app.post("/remove-item", (req, resp) => {
const data = req.body;
if (!data) { // Guard clause
resp.end();
}
const sessionId = req.cookies.session.substring(1);
const userId = sessions.get(sessionId);
if (!userId) {
resp.status(401);
resp.end();
} else {
console.log("Session valid. Removing item")
client.connect((err, client) => {
if (err) {
throw err;
} else {
// If DB connection is successful
const db = client.db("database");
db.collection("carts").findOne({"code": data.cartCode}, {}, (err, res) => {
if (err) {
throw err;
} else {
// Found user document
// Edit correct field
let array = null;
let field = null;
switch(data.itemType) {
case itemTypes.CANNEDJARRED:
array = res.cannedJarredData;
field = "cannedJarredData";
break;
case itemTypes.DAIRY:
array = res.dairyData;
field = "dairyData";
break;
case itemTypes.DRYBAKING:
array = res.dryBakingData;
field = "dryBakingData";
break;
case itemTypes.FROZEN:
array = res.frozenData;
field = "frozenData";
break;
case itemTypes.GRAINS:
array = res.grainsData;
field = "grainsData";
break;
case itemTypes.MEAT:
array = res.meatData;
field = "meatData";
break;
case itemTypes.PRODUCE:
array = res.produceData;
field = "produceData";
break;
case itemTypes.OTHER:
array = res.otherData;
field = "otherData";
break;
default:
array = null;
field = null;
break;
}
if (!array) {
resp.status(404);
resp.end();
}
array = array.filter(i => i !== data.itemName);
db.collection("carts").updateOne({"code": data.cartCode}, { $set: {[field]: array} }, (err, result) => {
if (err) {
throw err;
} else {
resp.status(200);
resp.end();
}
});
}
})
}
})
}
})
app.post("/logout", (req, resp) => {
const sessionId = req.cookies.session.substring(1);
if (sessionId) {
sessions.delete(sessionId);
resp.status(200);
resp.end();
} else {
resp.status(404);
resp.end();
}
})
app.post("/login", (req, resp) => {
// Check email and password
const data = req.body;
client.connect((err, client) => {
if (err) {
throw err;
} else {
// Connection succeeded
const db = client.db("database");
db.collection("users").findOne({"email": data.email}, {}, (err, res) => {
if (err) {
throw err;
} else {
if (res) {
// User exists
const hash = res.password;
bcrypt.compare(data.password, hash, (err, bcryptRes) => {
// Check if password is right
if (bcryptRes) {
const body = {
error: false,
homeCart: res.homeCart,
}
const sessionId = uuidv4();
sessions.set(sessionId, res._id);
resp.set("Set-Cookie", 'session=$' + sessionId);
resp.json(JSON.stringify(body));
console.log("user authenticated");
resp.end();
} else {
const body = {
error: true
}
resp.json(JSON.stringify(body));
resp.end();
}
})
} else {
const body = {
error: true
}
console.log("User does not exist.");
resp.json(JSON.stringify(body));
resp.end();
}
}
})
}
})
})
app.post("/register", (req, resp) => {
console.log("Registering new user...");
const data = req.body;
client.connect(async (err, client) => {
if (err) {
throw err;
} else {
// Connection succeeded
const db = client.db("database");
db.collection("users").findOne({"email": data.email}, {}, (err, res) => {
if (err) {
throw err;
} else {
if (res) {
const body = {
error: true
}
console.log("User already exists.");
resp.json(JSON.stringify(body));
resp.end();
} else {
// Hash pass
console.log("hashing pass...");
bcrypt.hash(data.password, saltRounds, async function(err, hash) {
const c = makeCode();
let success = await createCartFromCode(c);
if (success) {
const newUser = {
email: data.email,
password: hash,
homeCart: c,
}
db.collection("users").insertOne(newUser, (err, res) => {
// Insert to DB
if (err) {
throw err;
} else {
console.log("New user data sent to database!");
const body = {
error: false,
}
resp.json(JSON.stringify(body));
resp.end();
}
});
} else {
resp.status(400);
resp.json(JSON.stringify({error: true, code: null}));
resp.end();
}
})
}
}
})
}
})
});
function makeCode() {
var code = "";
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var charactersLength = characters.length;
for (let i = 0; i < 6; i++) {
code += characters.charAt(Math.floor(Math.random() * characters.length));
}
return code;
}
app.post("/create-cart", async (req, resp) => {
console.log("Creating a new cart...");
const c = makeCode();
let success = await createCartFromCode(c);
if (success) {
resp.status(200);
resp.json(JSON.stringify({error: false, code: c}));
resp.end();
} else {
resp.status(400);
resp.json(JSON.stringify({error: true, code: null}));
resp.end();
}
})
async function createCartFromCode(code) {
return new Promise((resolve, reject) => {
client.connect((err, client) => {
if (err) {
throw err;
} else {
// Connection succeeded
const newCart = {
code: code,
cannedJarredData: [],
dairyData: [],
dryBakingData: [],
frozenData: [],
grainsData: [],
meatData: [],
produceData: [],
otherData: []
}
const db = client.db("database");
db.collection("carts").insertOne(newCart, (err, res) => {
// Insert to DB
if (err) {
throw err;
} else {
console.log("New cart sent to database!");
resolve(true);
}
});
}
})
});
}
// Serve React build
app.use(express.static(__dirname + "/client/build"));
// Serve react app
app.get("*", (req, res) => {
res.sendFile(__dirname + "/client/build/index.html");
});