-
Notifications
You must be signed in to change notification settings - Fork 125
/
app.js
861 lines (768 loc) · 23.9 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
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const multer = require('multer');
const mongoose = require('mongoose');
const dotenv = require('dotenv').config();
const { body, validationResult } = require('express-validator');
const session = require('express-session');
const MongoStore = require('connect-mongo');
const bcrypt = require('bcrypt');
const cloudinary = require('cloudinary').v2;
const { CloudinaryStorage } = require('multer-storage-cloudinary');
const app = express();
const rateLimit = require('express-rate-limit');
const helmet = require('helmet');
const cors = require('cors');
// Import the database.js file
const { User, Food, House, Market, Feedback } = require('./database'); // Adjust path as needed
// Middleware to parse JSON and form data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public')); // Serve static files from 'public' directory
app.use(express.urlencoded({ extended: true })); // For parsing application/x-www-form-urlencoded
// Session setup
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
store: MongoStore.create({ mongoUrl: process.env.DB_URL }),
cookie: { secure: false }, // Set to true if using HTTPS
})
);
// Middleware to set user object for views
app.use((req, res, next) => {
res.locals.user = req.session.user; // Make user object available in views
next();
});
app.set('views', path.resolve(__dirname, 'views'));
app.set('view engine', 'ejs');
// Cloudinary configuration
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
// Configure CloudinaryStorage
const storage = new CloudinaryStorage({
cloudinary: cloudinary,
params: {
folder: 'uploads',
format: async (req, file) => 'jpeg', // Supports promises as well
public_id: (req, file) =>
Date.now() +
'-' +
file.originalname.replace(/[^a-zA-Z0-9_.-]/g, '_').slice(0, 100),
},
});
// Initialize multer with the Cloudinary storage
const upload = multer({ storage });
// Authentication middleware
const ensureAuthenticated = (req, res, next) => {
if (req.session.user) {
return next();
}
res.redirect('/auth?action=login');
};
// Routes
// Home route
app.get('/', (req, res) => {
res.render('index', {
searchAction: '/food',
selectedType: req.query.type || 'food',
query: req.query.query || '',
activeLink: 'home',
});
});
// Team route
app.get('/team', (req, res) => {
res.render('team', {
searchAction: '/food',
selectedType: req.query.type || 'food',
q: req.query.q || '',
activeLink: '',
});
});
// Render authentication page
app.get('/login', (req, res) => {
const action = req.query.action || 'login';
res.render('auth', { action, errors: [], activeLink: '' });
});
// Render authentication page
app.get('/auth', (req, res) => {
const action = req.query.action || 'login';
res.render('auth', { action, errors: [], activeLink: '' });
});
// Handle login form submission
app.post(
'/login',
[
body('username').notEmpty().withMessage('Username is required'),
body('password').notEmpty().withMessage('Password is required'),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('auth', {
action: 'login',
errors: errors.array(),
activeLink: '',
});
}
const { username, password } = req.body;
try {
const user = await User.findOne({ username });
console.log('Fetched User from MongoDB: ', user);
if (user && (await bcrypt.compare(password, user.password))) {
req.session.user = user;
res.redirect('/');
} else {
res.status(400).render('auth', {
action: 'login',
errors: [{ msg: 'Invalid credentials' }],
activeLink: '',
});
}
} catch (error) {
console.error('Error during login:', error);
res.status(500).render('500');
}
}
);
// Handle signup form submission
app.post(
'/signup',
[
body('username').notEmpty().withMessage('Username is required'),
body('email').isEmail().withMessage('Email is required and must be valid'),
body('password').notEmpty().withMessage('Password is required'),
body('confirmPassword')
.notEmpty()
.withMessage('Confirm Password is required'),
body('phone').notEmpty().withMessage('Phone number is required'),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('auth', {
action: 'signup',
errors: errors.array(),
activeLink: '',
});
}
const { username, email, password, confirmPassword, phone } = req.body;
if (password !== confirmPassword) {
return res.status(400).render('auth', {
action: 'signup',
errors: [{ msg: 'Passwords do not match' }],
activeLink: '',
});
}
try {
const existingUser = await User.findOne({
$or: [{ username }, { email }, { phone }],
});
if (existingUser) {
const errors = [];
if (existingUser.username === username) {
errors.push({ msg: 'Username is already taken' });
}
if (existingUser.phone === phone) {
errors.push({ msg: 'Phone is already taken' });
}
if (existingUser.email === email) {
errors.push({ msg: 'Email is already registered' });
}
return res
.status(400)
.render('auth', { action: 'signup', errors, activeLink: '' });
}
const hashedPassword = await bcrypt.hash(password, 10);
const newUser = new User({
username,
email,
password: hashedPassword,
phone,
});
await newUser.save();
req.session.user = newUser;
res.redirect('/');
} catch (error) {
console.error('Error during signup:', error);
res.status(500).render('auth', {
action: 'signup',
errors: [{ msg: 'Internal Server Error' }],
activeLink: '',
});
}
}
);
// POST route to handle feedback submission
app.post('/submit-feedback', async (req, res) => {
const { feedbackText, email } = req.body;
try {
const feedback = new Feedback({
feedbackText,
email,
});
await feedback.save();
res.status(201).json({ message: 'Feedback submitted successfully!' });
} catch (error) {
console.error('Error saving feedback:', error); // Log the error for debugging
res.status(500).json({ message: 'Error submitting feedback' });
}
});
//Change in Dashboard Stuff
//Updating Personal Information of Username and Email
app.post('/update-personal-info', ensureAuthenticated, (req, res) => {
if (!req.session.user || !req.session.user.username) {
return res.redirect('/login'); // Redirect if not logged in
}
const { username } = req.session.user;
const { newUsername, email } = req.body;
if (!newUsername || !email) {
return res.status(400).send('All fields are required.');
}
User.findOneAndUpdate(
{ username },
{ username: newUsername, email },
{ new: true }
)
.then(updatedUser => {
// Update session data after successful update
req.session.user = {
username: updatedUser.username,
email: updatedUser.email,
phone: updatedUser.phone,
};
res.redirect('/dashboard');
})
.catch(err => {
console.error(err);
res.status(500).send('Error updating user data.');
});
});
//Changing The Password
app.post('/change-password', ensureAuthenticated, (req, res) => {
const { currentPassword, newPassword } = req.body;
const { username } = req.session.user; // Fetch the username from the session
// Validate inputs
if (!currentPassword || !newPassword) {
return res.status(400).send('All fields are required.');
}
// Find the user by username instead of userId
User.findOne({ username })
.then(user => {
console.log('User found:', user); // Log the user object for debugging
if (!user) {
return res.status(404).send('User not found.');
}
// Check if the current password matches (using bcrypt)
return bcrypt.compare(currentPassword, user.password).then(isMatch => {
if (!isMatch) {
return res.status(400).send('Current password is incorrect.');
}
// Hash the new password and save it
return bcrypt.hash(newPassword, 10).then(hashedPassword => {
user.password = hashedPassword; // Update the password
return user.save(); // Save the updated user data
});
});
})
.then(() => {
res.redirect('/dashboard'); // Redirect to the dashboard after success
})
.catch(err => {
console.error('Error changing password:', err);
res.status(500).send('Error changing password.'); //Show Error when unsuccessful
});
});
//Updating Contact Info
app.post('/update-contact-info', ensureAuthenticated, (req, res) => {
const { phone } = req.body;
const { username } = req.session.user; // Fetch the username from the session
// Validate input data
if (!phone) {
return res.status(400).send('Phone number is required.');
}
// Update the user phone number in the database based on the username
User.findOneAndUpdate({ username }, { phone }, { new: true })
.then(updatedUser => {
// Update the session with the new contact information
req.session.user = {
username: updatedUser.username,
email: updatedUser.email,
phone: updatedUser.phone,
};
res.redirect('/dashboard'); // Redirect back to the dashboard
})
.catch(err => {
console.error('Error updating contact information:', err);
res.status(500).send('Error updating contact information.');
});
});
// Handle logout
app.get('/logout', (req, res) => {
req.session.destroy(err => {
if (err) {
console.error('Error during logout:', err);
res.status(500).render('500');
} else {
res.redirect('/');
}
});
});
// Express Route to render the User Dashboard page
app.get('/dashboard', ensureAuthenticated, (req, res) => {
const user = req.session.user; // Accessing user from session
res.render('dashboard', { user, activeLink: 'userdashboard' });
});
//About Page Route
app.get('/about', (req, res) => {
res.render('about', {
title: 'About Us - Scruter',
appName: 'Scruter',
activeLink: 'about',
});
});
// Contributors Route
app.get('/contributors', (req, res) => {
res.render('contributors', { activeLink: 'contributors' });
});
// Terms route
app.get('/terms', (req, res) => {
res.render('terms', {
activeLink: 'terms', // You can customize this based on your layout
});
});
app.get('/contact', (req, res) => {
res.render('contact', {
activeLink: 'contact', // You can customize this based on your layout
});
});
app.get('/faq', (req, res) => {
res.render('faq', {
activeLink: 'faq', // You can customize this based on your layout
});
});
app.get('/help', (req, res) => {
res.render('help', {
activeLink: 'help', // You can customize this based on your layout
});
});
app.get('/support', (req, res) => {
res.render('support', {
activeLink: 'support', // You can customize this based on your layout
});
});
app.get('/privacy-policy', (req, res) => {
res.render('privacy-policy', {
activeLink: 'privacy-policy', // You can customize this based on your layout
});
});
// Render form pages with authentication check
app.get('/food/form', ensureAuthenticated, (req, res) => {
res.render('form', { routeName: 'food', errors: [], activeLink: 'food' });
});
app.get('/house/form', ensureAuthenticated, (req, res) => {
res.render('form', { routeName: 'house', errors: [], activeLink: 'house' });
});
app.get('/market/form', ensureAuthenticated, (req, res) => {
res.render('form', { routeName: 'market', errors: [], activeLink: 'market' });
});
app.get('/:type/edit/:id', ensureAuthenticated, async (req, res) => {
const { id, type } = req.params;
if (!['food', 'house', 'market'].includes(type))
return res.status(400).render('400');
const Model = type === 'food' ? Food : type === 'house' ? House : Market;
const item = await Model.findById(id).catch(() => {});
if (!item) return res.status(404).render('404');
if (req.session.user.username !== item.username)
return res.status(500).render('500');
res.render('edit', { item, type, activeLink: type });
});
// Handle search and display for houses
app.get('/house', async (req, res) => {
try {
const domain = req.get('host');
const query = req.query.query || '';
const sort = req.query.sort || ''; // Get the sort parameter from query
const searchRegex = new RegExp(query, 'i');
// Build the sort object based on the query parameter
let sortOptions = {};
if (sort === 'asc') {
sortOptions.rent = 1; // Sort by rent ascending
} else if (sort === 'desc') {
sortOptions.rent = -1; // Sort by rent descending
}
const houses = await House.find({
$or: [
{ title: searchRegex },
{ location: searchRegex },
{ description: searchRegex },
],
}).sort(sortOptions);
res.render('display', {
cards: houses,
domain,
imagepath: '/house.webp',
query,
selectedType: 'house',
searchAction: '/house',
activeLink: 'house',
});
} catch (error) {
console.error('Error fetching houses:', error);
res.status(500).render('500');
}
});
// Handle form submission for houses
app.post(
'/house',
upload.single('image'),
[
body('title').notEmpty().withMessage('Title is required'),
body('location').notEmpty().withMessage('Location is required'),
body('rent').isNumeric().withMessage('Rent must be a number'),
body('latitude').notEmpty().withMessage('Latitude is required'),
body('longitude').notEmpty().withMessage('Longitude is required'),
body('description').notEmpty().withMessage('Description is required'),
body('email').isEmail().withMessage('Email is required and must be valid'), //email
body('phone').notEmpty().withMessage('Phone number is required'), //phone
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('form', {
routeName: 'house',
errors: errors.array(),
activeLink: 'house',
});
}
try {
const {
title,
location,
rent,
latitude,
longitude,
description,
email,
phone,
} = req.body;
const username = req.session.user.username;
const result = await cloudinary.uploader.upload(req.file.path);
const house = new House({
title,
location,
rent,
latitude,
longitude,
description,
image: result.secure_url,
username,
email, //email
phone, //phone
});
await house.save();
res.redirect('/house');
} catch (error) {
console.error('Error saving house:', error);
res.status(500).render('form', {
routeName: 'house',
errors: [{ msg: 'Internal Server Error' }],
activeLink: 'house',
});
}
}
);
app.post(
'/edit/:type/:id',
upload.single('image'),
[
body('title').notEmpty().withMessage('Title is required'),
body('location').notEmpty().withMessage('Location is required'),
body('latitude').notEmpty().withMessage('Latitude is required'),
body('longitude').notEmpty().withMessage('Longitude is required'),
body('description').notEmpty().withMessage('Description is required'),
body('email').isEmail().withMessage('Email is required and must be valid'),
body('phone').notEmpty().withMessage('Phone number is required'),
body('rent').custom((value, { req }) =>
req.params.type === 'house' ? value !== '' && !isNaN(value) : true
),
body('price').custom((value, { req }) =>
req.params.type === 'market' ? value !== '' && !isNaN(value) : true
),
],
async (req, res) => {
const { type, id } = req.params;
if (!['food', 'house', 'market'].includes(type))
return res.status(400).render('400');
const errors = validationResult(req);
if (!errors.isEmpty())
return res.status(400).render(`/edit/${type}/${id}`, {
type: req.params.type,
errors: errors.array(),
activeLink: req.params.activeLink,
});
const Model = type === 'food' ? Food : type === 'house' ? House : Market;
const item = await Model.findById(id).catch(() => {});
if (!item) return res.status(404).render('404');
if (req.session.user.username !== item.username)
return res.status(500).render('500');
if (req.file) {
const result = await cloudinary.uploader.upload(req.file.path);
item.image = result.secure_url;
}
Object.assign(item, req.body);
await item.save();
return res.redirect(`/${type}`);
}
);
// Handle search and display for market
// Handle search and display for market
app.get('/market', async (req, res) => {
try {
const domain = req.get('host');
const query = req.query.query || '';
const sort = req.query.sort || ''; // Get the sort parameter from query
const searchRegex = new RegExp(query, 'i');
// Build the sort object based on the query parameter
let sortOptions = {};
if (sort === 'asc') {
sortOptions.price = 1; // Sort by price ascending
} else if (sort === 'desc') {
sortOptions.price = -1; // Sort by price descending
}
const markets = await Market.find({
$or: [
{ title: searchRegex },
{ location: searchRegex },
{ description: searchRegex },
],
}).sort(sortOptions); // Apply sorting
res.render('display', {
cards: markets,
domain,
imagepath: '/market.webp',
query,
selectedType: 'market',
searchAction: '/market',
activeLink: 'market',
});
} catch (error) {
console.error('Error fetching markets:', error);
res.status(500).render('500');
}
});
// Handle form submission for market
app.post(
'/market',
upload.single('image'),
[
body('title').notEmpty().withMessage('Title is required'),
body('location').notEmpty().withMessage('Location is required'),
body('price').isNumeric().withMessage('Price must be a number'),
body('latitude').notEmpty().withMessage('Latitude is required'),
body('longitude').notEmpty().withMessage('Longitude is required'),
body('description').notEmpty().withMessage('Description is required'),
body('email').isEmail().withMessage('Email is required and must be valid'),
body('phone').notEmpty().withMessage('Phone number is required'),
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('form', {
routeName: 'market',
errors: errors.array(),
activeLink: 'market',
});
}
try {
const {
title,
location,
price,
latitude,
longitude,
description,
email,
phone,
} = req.body;
const username = req.session.user.username;
const result = await cloudinary.uploader.upload(req.file.path);
const market = new Market({
title,
location,
price,
latitude,
longitude,
description,
image: result.secure_url,
username,
email, //email
phone, //phone
});
await market.save();
res.redirect('/market');
} catch (error) {
console.error('Error saving market item:', error);
res.status(500).render('form', {
routeName: 'market',
errors: [{ msg: 'Internal Server Error' }],
activeLink: 'market',
});
}
}
);
// Handle search and display for food
app.get('/food', async (req, res) => {
try {
const domain = req.get('host');
const query = req.query.query || '';
const sort = req.query.sort || ''; // Get the sort parameter from query
const searchRegex = new RegExp(query, 'i');
// Build the sort object based on the query parameter
let sortOptions = {};
if (sort === 'asc') {
sortOptions.price = 1; // Sort by price ascending
} else if (sort === 'desc') {
sortOptions.price = -1; // Sort by price descending
}
const foods = await Food.find({
$or: [
{ title: searchRegex },
{ location: searchRegex },
{ description: searchRegex },
],
}).sort(sortOptions); // Apply sorting
res.render('display', {
cards: foods,
domain,
imagepath: '/food.webp',
query,
selectedType: 'food',
searchAction: '/food',
activeLink: 'food',
});
} catch (error) {
console.error('Error fetching foods:', error);
res.status(500).render('500');
}
});
// Handle form submission for food
app.post(
'/food',
upload.single('image'),
[
body('title').notEmpty().withMessage('Title is required'),
body('location').notEmpty().withMessage('Location is required'),
body('latitude').notEmpty().withMessage('Latitude is required'),
body('longitude').notEmpty().withMessage('Longitude is required'),
body('description').notEmpty().withMessage('Description is required'),
body('email').isEmail().withMessage('Email is required and must be valid'), //email
body('phone').notEmpty().withMessage('Phone number is required'), //phone
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('form', {
routeName: 'food',
errors: errors.array(),
activeLink: 'food',
});
}
try {
const {
title,
location,
latitude,
longitude,
description,
email,
phone,
} = req.body;
const username = req.session.user.username;
const result = await cloudinary.uploader.upload(req.file.path);
const food = new Food({
title,
location,
latitude,
longitude,
description,
image: result.secure_url,
username,
email, //email
phone, //phone
});
await food.save();
res.redirect('/food');
} catch (error) {
console.error('Error saving food item:', error);
res.status(500).render('form', {
routeName: 'food',
errors: [{ msg: 'Internal Server Error' }],
activeLink: 'food',
});
}
}
);
app.post('/delete/:type/:id', ensureAuthenticated, async (req, res) => {
const { type, id } = req.params;
const { username } = req.session.user;
try {
let Model;
let item;
switch (type) {
case 'food':
Model = Food;
break;
case 'house':
Model = House;
break;
case 'market':
Model = Market;
break;
default:
res.status(500).render('500');
}
// Find the item to delete
item = await Model.findOne({ _id: id });
if (!item) {
res.status(500).render('500');
}
// Check if the user is "admin" or owns the item
if (username === 'admin' || item.username === username) {
// Delete the item from the database
await Model.deleteOne({ _id: id });
return res.redirect(`/${type}`);
} else {
res.status(500).render('500');
}
} catch (error) {
console.error(`Error deleting ${type}:`, error);
res.status(500).render('500');
}
});
// 404 Error Handler
app.use((req, res) => {
res.status(404).render('404');
});
// 500 Error Handler
app.use((err, req, res, next) => {
console.error('Internal Server Error:', err);
res.status(500).render('500');
});
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
});
app.use(limiter);
app.use(helmet());
app.use(cors());
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});