-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi.js
More file actions
675 lines (633 loc) · 20.9 KB
/
api.js
File metadata and controls
675 lines (633 loc) · 20.9 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
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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
const nodemailer = require('nodemailer');
const jwt = require('jsonwebtoken');
require('dotenv').config();
const cors = require('cors');
const bcrypt = require('bcrypt');
let transporter;
const { ObjectId } = require('mongodb');
const bp = require('./web_frontend/src/components/Path.js');
const fs = require('fs').promises;
exports.setApp = function (app, client) {
transporter = nodemailer.createTransport({
host: 'smtp.forwardemail.net',
port: 587,
secure: false,
auth: {
user: process.env.VerificationEmail,
pass: process.env.VerificationEmailPassword
},
from: process.env.VerificationEmail
});
app.post('/api/updatePassword', async (req, res) => {
const { token, password } = req.body;
if (!token || !password) {
return res.status(400).json({ error: 'Request missing token or password.' });
}
try {
// Verify the token is valid and not expired
const decoded = jwt.verify(token, process.env.KeyTheJWT);
const userId = decoded.userId;
// Check if the user exists
const db = client.db('MegaBitesLibrary');
const user = await db.collection('User').findOne({ _id: new ObjectId(userId) });
if (!user) {
return res.status(404).json({ error: 'User not found.' });
}
const updatePassHash = await bcrypt.hash(password, 10);
// Update the user's password in the database
// Instead of hashing the new password, we directly set the Password field
await db.collection('User').updateOne(
{ _id: user._id },
{ $set: { Password: updatePassHash } } // Overwrite the old password with the new one
);
console.log('Password updated successfully for user:', user.Username);
res.status(200).json({ message: 'Password updated successfully.' });
} catch (error) {
if (error.name === 'JsonWebTokenError') {
res.status(400).json({ error: 'Invalid token.' });
} else if (error.name === 'TokenExpiredError') {
res.status(400).json({ error: 'Token expired.' });
} else {
console.error('Update Password error:', error);
res.status(500).json({ error: 'Error updating password.' });
}
}
});
app.post('/api/forgotPassword', async (req, res) => {
const { email } = req.body;
try {
const db = client.db('MegaBitesLibrary');
const user = await db.collection('User').findOne({ Email: email.toLowerCase() });
if (!user) {
return res.status(404).json({ error: 'User with that email does not exist.' });
}
const token = jwt.sign({ userId: user._id }, process.env.KeyTheJWT, {
expiresIn: '1h', // The token will expire in 1 hour
});
await db.collection('User').updateOne(
{ _id: user._id },
{
$set: {
resetPasswordToken: token,
resetPasswordExpires: new Date(Date.now() + 3600000), // 1 hour from now
},
}
);
const resetLink = `http://megabytes.app/resetPassword?token=${token}`;
//const resetLink = `http://localhost:5000/resetPassword?token=${token}`;
//const resetLink = `http://localhost:3000/resetPassword?token=${token}`;
const mailOptions = {
from: process.env.VerificationEmail,
to: email,
subject: 'Password Reset',
text: `Please use the following link to reset your password: ${resetLink}`,
};
await new Promise((resolve, reject) => {
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
reject(error);
} else {
resolve(info);
}
});
});
console.log('Password reset email sent successfully');
res.status(200).json({ message: 'Password reset email sent successfully, please wait here to be redirected.' });
} catch (error) {
console.error('Forgot Password error:', error);
res.status(500).json({ error: 'Error processing forgot password.' });
}
});
app.post('/api/verifyEmail', async (req, res) => {
const { username, password, email } = req.body;
const hashedPassword = await bcrypt.hash(password, 10);
// Include user information in the token payload
const tokenPayload = {
username,
password: hashedPassword,
email,
};
const token = jwt.sign(tokenPayload, process.env.KeyTheJWT, {
expiresIn: '1h',
});
const verificationLink = `https://megabytes.app/verify?token=${token}`;
//const verificationLink = `http://localhost:5000/verify?token=${token}`;
const mailOptions = {
from: process.env.VerificationEmail,
to: email,
subject: 'Email Verification',
text: `Please use the following link to verify your email and create your account: ${verificationLink}`,
};
transporter.sendMail(mailOptions, (error, info) => {
if (error) {
console.error('Error sending email:', error);
res.status(500).json({ error: 'Error sending email' }); // Send JSON response here
} else {
console.log('Email sent: ' + info.response);
res.status(200).json({ message: 'Email sent successfully, please verify your account and then return to the login page' }); // Send JSON response here
}
});
});
app.get('/verify', async (req, res) => {
console.log('Received a request to /verify');
const token = req.query.token;
jwt.verify(token, process.env.KeyTheJWT, async (err, decoded) => {
if (err) {
console.error('Error verifying token:', err);
res.status(400).json({ error: 'Invalid token' });
} else {
const { username, password, email } = decoded;
console.log('Decoded Token:', decoded);
console.log('Extracted User Info - Username:', username);
console.log('Extracted User Info - Password:', password);
console.log('Extracted User Info - Email:', email);
const db = client.db('MegaBitesLibrary');
// Check if the user has already been registered (flag set)
const existingUser = await db.collection('User').findOne({ Username: username, Email: email.toLowerCase(), IsVerified: true });
if (existingUser) {
console.log('User already registered and verified:', existingUser);
return res.status(200).json('Email already verified. Please return to the login page.');
}
// Proceed with registration and set the IsVerified flag
const newUser = {
Username: username,
Password: password,
Email: email.toLowerCase(),
RecipeList: [],
IsVerified: true // Set the flag to indicate successful verification
};
var error = '';
try {
await db.collection('User').insertOne(newUser);
} catch (e) {
error = e.toString();
}
if (error) {
res.status(500).json({ error });
} else {
//res.status(200)//.json('Email verified successfully and account created! Please return to the login page 👍');
res.redirect('https://megabytes.app');
}
}
});
});
app.post('/api/register', async (req, res, next) => {
// incoming: username, password, email
// outgoing: error
const { username, password, email } = req.body;
const newUser = { Username: username, Password: password, Email: email, RecipeList: [] };
var error = '';
try {
const db = client.db('MegaBitesLibrary');
db.collection('User').insertOne(newUser);
}
catch (e) {
error = e.toString();
}
var ret = { error: error };
res.status(200).json(ret);
});
app.post('/api/deleteUser', async (req, res, next) => {
// incoming: userId
// outgoing: error
let error = '';
const { userId } = req.body;
const filter = { _id: new ObjectId(userId) };
const db = client.db('MegaBitesLibrary');
const results = await db.collection('User').findOne(filter);
const recipes = results.RecipeList;
if(recipes){
for (let i = 0; i < recipes.length; i++) {
var obj = { recipeId: recipes[i]._id };
var js = JSON.stringify(obj);
try {
await fetch(bp.buildPath('api/deleteRecipe'),
{
method: 'POST', body: js, headers: {
'Content-Type':
'application/json'
}
});
}
catch (e) {
error = e.toString();
var ret = { error: error };
res.status(500).json(ret);
}
}
}
db.collection('User').deleteOne(filter, (err, result) => {
if (err) {
console.error('Error deleting document:', err);
} else {
console.log('Deleted document successfully');
}
});
var ret = { error: error };
res.status(200).json(ret);
});
app.post('/api/login', async (req, res, next) => {
// incoming: login, password
// outgoing: id, error
let error = '';
const { username, password } = req.body;
try {
const db = client.db('MegaBitesLibrary');
const isEmail = await db.collection('User').find({ Email: username }).toArray();
const isUser = await db.collection('User').find({ Username: username }).toArray();
var user
if (isUser.length == 0 && isEmail.length == 0) {
return res.status(401).json({ error: 'Invalid credentials ' });
} else if(isUser.length == 0){
user = isEmail
} else {
user = isUser
}
const passwordMatch = await bcrypt.compare(password, user[0].Password);
if (passwordMatch) {
res.status(200).json({ id: user[0]._id, username: user[0].Username, error: '' });
} else {
res.status(401).json({ error: 'Invalid credentials' });
}
}
catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/addRecipe', async (req, res) => {
// incoming: userId, recipeName, recipeContents, tagList, likeList
// outgoing: error
const { userId, recipeName, recipeContents, tagList, likeList, isPublic, ai_generated } = req.body;
const newRecipe = {
UserId: new ObjectId(userId),
RecipeName: recipeName,
RecipeContents: recipeContents,
TagList: tagList,
LikeList: likeList,
IsPublic: isPublic,
CommentList: [],
AI_Generated: ai_generated,
};
try {
const db = client.db('MegaBitesLibrary');
// Insert new recipe into Recipes collection
const insertResult = await db.collection('Recipes').insertOne(newRecipe);
const recipeId = insertResult.insertedId;
// Update the user's RecipeList with the new recipe
const updateResult = await db.collection('User').updateOne(
{ _id: new ObjectId(userId) },
{ $push: { RecipeList: { _id: recipeId } } }
);
console.log(updateResult);
res.status(200).json({ error: null });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/updateRecipeLikes', async (req, res, next) => {
// incoming: userID, recipeID
// outputs: update value, error
const { userID, recipeID } = req.body;
try {
const db = client.db('MegaBitesLibrary');
const recipe = await db.collection('Recipes').findOne({ _id: new ObjectId(recipeID) });
let update = 0;
if (!recipe) {
return res.status(404).json({ error: 'Reicpe not found' });
}
if (!(recipe.LikeList.includes(userID))) {
await db.collection('Recipes').updateOne(
{ _id: new ObjectId(recipeID) },
{ $push: { LikeList: userID } }
);
update = 1;
} else {
await db.collection('Recipes').updateOne(
{ _id: new ObjectId(recipeID) },
{ $pull: { LikeList: userID } }
);
update = -1;
}
res.status(200).json({ update: update, error: null });
} catch (error) {
console.error('Error updating likes', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/deleteRecipe', async (req, res, next) => {
// incoming: recipeId
// outgoing: error
var error = '';
const { recipeId } = req.body;
const filter = { _id: new ObjectId(recipeId) };
const db = client.db('MegaBitesLibrary');
const results = await db.collection('Recipes').findOne(filter);
const comments = results.CommentList;
if(comments){
for (let i = 0; i < comments.length; i++) {
let commentFilter = comments[i];
db.collection('Comments').deleteOne(commentFilter, (err, result) => {
if (err) {
console.error('Error deleting document:', err);
} else {
console.log('Deleted document successfully');
}
});
}
}
const user = await db.collection('User').findOne({ _id: results.UserId });
if(user){
await db.collection('User').updateOne(
{ _id: user._id },
{ $pull: { RecipeList: { _id: new ObjectId(recipeId) } } }
);
}
db.collection('Recipes').deleteOne(filter, (err, result) => {
if (err) {
console.error('Error deleting document:', err);
} else {
console.log('Deleted document successfully');
}
});
var ret = { error: error };
res.status(200).json(ret);
});
app.post('/api/getUserRecipes', async (req, res, netx) => {
// incoming: userID
// outgoing: results[], error
try {
const { userID } = req.body;
if (!userID) {
return res.status(400).json({ error: 'userID is required' });
}
const db = client.db('MegaBitesLibrary');
const user = await db.collection('User').findOne({ _id: new ObjectId(userID) });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
const recipeList = user.RecipeList || [];
const recipeIds = recipeList.map(recipe => recipe._id);
res.json({ results: recipeIds, error: '' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal error' });
}
});
app.post('/api/getPublicRecipes', async (req, res, netx) => {
// incoming:
// outgoing: results[], error
try {
const db = client.db('MegaBitesLibrary');
const publicRecipes = await db.collection('Recipes').find({ IsPublic: true}).toArray();
const results = [];
for (let i = 0; i < publicRecipes.length; i++)
{
results.push(publicRecipes[i]._id);
}
res.json({ results: results, error: '' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal error' });
}
});
app.post('/api/getRecipeByID', async (req, res, next) => {
// incoming recipeID
// outgoing: recipe, error
try {
const { recipeID } = req.body;
if (!recipeID) {
return res.status(400).json({ error: 'recipeID is required' });
}
const db = client.db('MegaBitesLibrary');
const recipe = await db.collection('Recipes').findOne({ _id: new ObjectId(recipeID) });
if (!recipe) {
return res.status(404).json({ error: 'Recipe not found' });
}
res.json({ results: recipe, error: '' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal error' });
}
});
app.post('/api/getUser', async (req, res, next) => {
// incoming userId
// outgoing: recipe, error
try {
const { userId } = req.body;
if (!userId) {
return res.status(400).json({ error: 'userId is required' });
}
const db = client.db('MegaBitesLibrary');
const user = await db.collection('User').findOne({ _id: new ObjectId(userId) });
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json({ results: user, error: '' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal error' });
}
});
app.post('/api/getRecipes', async (req, res, next) => {
// incoming: userId, search, isPublic
// outgoing: results[], error
var error = '';
var results;
const { userId, search, isPublic } = req.body;
var _search = search.trim();
const db = client.db('MegaBitesLibrary');
try {
if (isPublic) {
results = await
db.collection('Recipes').find({
"IsPublic": true,
"RecipeName": {
$regex: _search + '.*',
$options: 'i'
}
}).toArray();
} else {
results = await
db.collection('Recipes').find({
"UserId": new ObjectId(userId),
"RecipeName": {
$regex: search + '.*',
$options: 'i'
}
}).toArray();
}
} catch (e) {
console.error(e);
res.status(500).json({ e: 'Internal error' });
}
var ret = { results: results, error: error, };
res.status(200).json(ret);
});
app.post('/api/addComment', async (req, res, next) => {
// incoming: recipeId, userId, commentId, commentText
// outgoing: error
const { recipeId, userId, commentText } = req.body;
const newComment = {
RecipeId: new ObjectId(recipeId),
UserId: new ObjectId(userId),
CommentText: commentText
};
try {
const db = client.db('MegaBitesLibrary');
const insertResult = await db.collection('Comments').insertOne(newComment);
const commentId = insertResult.insertedId;
// Update the user's RecipeList with the new recipe
const updateResult = await db.collection('Recipes').updateOne(
{ _id: new ObjectId(recipeId) },
{ $push: { CommentList: { _id: commentId } } }
);
console.log(updateResult);
res.status(200).json({ commentId: commentId, error: null });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/getCommentByID', async (req, res, next) => {
// incoming: commentID
// outgoing: comment information
try {
const { commentID } = req.body;
if (!commentID) {
return res.status(400).json({ error: 'commentID is required' });
}
const db = client.db('MegaBitesLibrary');
const comment = await db.collection('Comments').findOne({ _id: new ObjectId(commentID) });
if (!comment) {
return res.status(404).json({ error: 'Comment not found' });
}
res.json({ results: comment, error: '' });
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Internal error' });
}
});
app.post('/api/updateCommentLikes', async (req, res, next) => {
// incoming: userID, commentID
const { userID, commentID } = req.body;
try {
const db = client.db('MegaBitesLibrary');
const comment = await db.collection('Comments').findOne({ _id: new ObjectId(commentID) });
let updateStatus = 0;
if (!comment) {
return res.status(404).json({ error: 'Comment not found' });
}
if (!(comment.LikeList.includes(userID))) {
await db.collection('Comments').updateOne(
{ _id: new ObjectId(commentID) },
{ $push: { LikeList: userID } }
);
updateStatus = 1;
} else {
await db.collection('Comments').updateOne(
{ _id: new ObjectId(commentID) },
{ $pull: { LikeList: userID } }
);
updateStatus = -1;
}
res.json({ update: updateStatus, error: '' });
} catch (error) {
console.error('Error updating likes', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
app.post('/api/deleteComment', async (req, res, next) => {
// incoming: commentId
// outgoing: error
var error = '';
const { commentId } = req.body;
const filter = { _id: new ObjectId(commentId) };
const db = client.db('MegaBitesLibrary');
const results = await db.collection('Comments').findOne(filter);
const recipe = await db.collection('Recipes').findOne({ _id: results.RecipeId });
await db.collection('Recipes').updateOne(
{ _id: recipe._id },
{ $pull: { CommentList: { _id: new ObjectId(commentId) } } }
);
db.collection('Comments').deleteOne(filter, (err, result) => {
if (err) {
console.error('Error deleting document:', err);
} else {
console.log('Deleted document successfully');
}
});
var ret = { recipe: recipe, error: error };
res.status(200).json(ret);
});
app.post('/api/editRecipe', async (req, res, next) => {
// incoming: recipeID, recipeName, recipeContents, tagList, likeList
// outgoing: error
var error = '';
const { recipeId, recipeName, recipeContents, tagList, likeList } = req.body;
const updateInfo = { RecipeName: recipeName, RecipeContents: recipeContents, TagList: tagList, LikeList: likeList }
const db = client.db('MegaBitesLibrary');
try {
const result = await db.collection('Recipes').updateOne(
{ _id: new ObjectId(recipeId) },
{ $set: updateInfo }
);
res.json({ message: `${result.nModified} document(s) updated` });
} catch (error) {
res.status(500).json({ error: error.message });
}
var ret = { error: error };
res.status(200).json(ret);
});
app.post('/api/editComment', async (req, res, next) => {
// incoming: commentID, commentText
// outgoing: error
var error = '';
const { commentId, commentText } = req.body;
const updateInfo = { CommentText: commentText }
const db = client.db('MegaBitesLibrary');
try {
const result = await db.collection('Comments').updateOne(
{ _id: new ObjectId(commentId) },
{ $set: updateInfo }
);
res.json({ message: `${result.nModified} document(s) updated` });
} catch (error) {
res.status(500).json({ error: error.message });
}
var ret = { error: error };
res.status(200).json(ret);
});
const getTags = async () => {
try {
const data = await fs.readFile('./tags.json', 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('Error reading tags from file', error);
return [];
}
};
app.get('/api/tags', async (req, res) => {
const tags = await getTags();
res.json(tags);
});
/*
app.post('/api/getComments', async (req, res, next) => {
// incoming: search
// outgoing: results[], error
var error = '';
const { search } = req.body;
var _search = search.trim();
const db = client.db('MegaBitesLibrary');
const results = await
db.collection('Comments').find({
"RecipeName": {
$regex: _search + '.*',
$options: 'i'
}
}).toArray();
var ret = { results: results, error: error };
res.status(200).json(ret);
});*/
}