forked from swarooppatilx/scruter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
480 lines (417 loc) · 14.2 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
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();
// 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
// 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 });
// Connect to MongoDB
mongoose.connect(process.env.DB_URL)
.then(() => console.log('Connected to MongoDB'))
.catch(error => console.error('Error connecting to MongoDB:', error));
// Schemas and Models
const foodSchema = new mongoose.Schema({
title: String,
image: String,
location: String,
latitude: String,
longitude: String,
description: String,
username: { type: String, required: true }
});
const Food = mongoose.model('Food', foodSchema);
const houseSchema = new mongoose.Schema({
title: String,
image: String,
location: String,
rent: Number,
latitude: String,
longitude: String,
description: String,
username: { type: String, required: true }
});
const House = mongoose.model('House', houseSchema);
const marketSchema = new mongoose.Schema({
title: String,
image: String,
location: String,
price: Number,
latitude: String,
longitude: String,
description: String,
username: { type: String, required: true }
});
const Market = mongoose.model('Market', marketSchema);
const userSchema = new mongoose.Schema({
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true }
});
const User = mongoose.model('User', userSchema);
// 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 });
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')
], 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 } = 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 }] });
if (existingUser) {
const errors = [];
if (existingUser.username === username) {
errors.push({ msg: 'Username 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 });
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: '' });
}
});
// 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('/');
}
});
});
// 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' });
});
// Handle search and display for houses
app.get('/house', async (req, res) => {
try {
const domain = req.get('host');
const query = req.query.query || '';
const searchRegex = new RegExp(query, 'i');
const houses = await House.find({
$or: [
{ title: searchRegex },
{ location: searchRegex },
{ description: searchRegex }
]
});
res.render('display', { cards: houses, domain, imagepath: "/house.jpg", 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')
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('form', { routeName: 'house', errors: errors.array(), activeLink: 'house' });
}
const { title, location, rent, latitude, longitude, description } = req.body;
const username = req.session.user.username;
try {
const result = await cloudinary.uploader.upload(req.file.path);
const house = new House({
title,
location,
rent,
latitude,
longitude,
description,
image: result.secure_url,
username
});
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' });
}
});
// Handle search and display for market
app.get('/market', async (req, res) => {
try {
const domain = req.get('host');
const query = req.query.query || '';
const searchRegex = new RegExp(query, 'i');
const markets = await Market.find({
$or: [
{ title: searchRegex },
{ location: searchRegex },
{ description: searchRegex }
]
});
res.render('display', { cards: markets, domain, imagepath: "/market.jpg", 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')
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('form', { routeName: 'market', errors: errors.array(), activeLink: 'market' });
}
const { title, location, price, latitude, longitude, description } = req.body;
const username = req.session.user.username;
try {
const result = await cloudinary.uploader.upload(req.file.path);
const market = new Market({
title,
location,
price,
latitude,
longitude,
description,
image: result.secure_url,
username
});
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 searchRegex = new RegExp(query, 'i');
const foods = await Food.find({
$or: [
{ title: searchRegex },
{ location: searchRegex },
{ description: searchRegex }
]
});
res.render('display', { cards: foods, domain, imagepath: "/food.jpg", 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')
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).render('form', { routeName: 'food', errors: errors.array(), activeLink: 'food' });
}
const { title, location, latitude, longitude, description } = req.body;
const username = req.session.user.username;
try {
const result = await cloudinary.uploader.upload(req.file.path);
const food = new Food({
title,
location,
latitude,
longitude,
description,
image: result.secure_url,
username
});
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');
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});