-
Notifications
You must be signed in to change notification settings - Fork 5
/
server.js
311 lines (278 loc) · 9.05 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
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const { body, validationResult } = require('express-validator');
const sanitizeHtml = require('sanitize-html');
const Item = require('./models/Item');
const User = require('./models/User');
const app = express();
const flash = require('express-flash');
const CURRENCY = process.env.CURRENCY || 'GBP';
const LIST_NAME = process.env.LIST_NAME || 'My Wishlist';
const LIST_TYPE = process.env.LIST_TYPE || 'bday';
const DBHOST = process.env.DBHOST || 'localhost:27017';
const DBNAME = process.env.DBNAME || 'simple-wishlist';
const PORT = process.env.PORT || 8092;
// Currency symbols mapping
const currencySymbols = {
'USD': '$',
'GBP': '£',
'EUR': '€',
};
// List Types
const occasion = {
'bday': 'wishlist-present.png',
'xmas': 'wishlist-xmas.png',
'wedding': 'wishlist-wedding.png',
};
const connectWithRetry = (retries) => {
return mongoose.connect(`mongodb://${DBHOST}/${DBNAME}`, {
serverSelectionTimeoutMS: 3000,
})
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
if (retries > 0) {
console.log(`MongoDB connection failed: (mongodb://${DBHOST}/${DBNAME}).`);
console.log(`Retrying... (${retries} attempts left)`);
setTimeout(() => connectWithRetry(retries - 1), 1000);
} else {
console.error(`Failed to connect to (mongodb://${DBHOST}/${DBNAME}) after multiple attempts.`);
console.error(err);
console.error('App Shutting Down...');
process.exit(1);
}
});
};
connectWithRetry(3);
app.use(session({
secret: process.env.SESSION_SECRET || 'yjtfkuhgkuygibjlljbvkuvykjvjlkvv',
resave: false,
saveUninitialized: false
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.set('view engine', 'ejs');
app.use(express.urlencoded({ extended: true }));
app.use(express.static('public'));
passport.use(new LocalStrategy(async (username, password, done) => {
try {
console.log('Login attempt for username:', username);
const user = await User.findOne({ username: username });
if (!user) {
console.log('User not found:', username);
return done(null, false, { message: 'Incorrect username.' });
}
const isValid = await bcrypt.compare(password, user.password);
if (!isValid) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
} catch (err) {
console.error('Error during login:', err);
return done(err);
}
}));
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser(async (id, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (err) {
done(err);
}
});
const auth = (req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/login');
};
const checkAdminSetup = async (req, res, next) => {
const adminCount = await User.countDocuments();
if (adminCount === 0) {
return res.redirect('/setup');
}
next();
};
app.use((req, res, next) => {
if (req.path !== '/setup') {
return checkAdminSetup(req, res, next);
}
next();
});
app.get('/setup', async (req, res) => {
const adminCount = await User.countDocuments();
if (adminCount === 0) {
res.render('setup', {
listType: occasion[LIST_TYPE]
});
} else {
res.redirect('/login');
}
});
app.post('/setup', [
body('username').trim().isLength({ min: 3 }).escape(),
body('password').trim().isLength({ min: 4 })
], async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
console.log('Validation errors:', errors.array());
return res.status(400).json({ errors: errors.array() });
}
const adminCount = await User.countDocuments();
if (adminCount === 0) {
const { username, password } = req.body;
console.log('Setting up admin user:', username);
const hashedPassword = await bcrypt.hash(password, 10);
const user = new User({ username, password: hashedPassword });
await user.save();
console.log('Admin user created successfully');
req.flash('success', 'Admin user created successfully. Please log in.');
return res.redirect(302, '/login');
} else {
console.log('Admin user already exists');
req.flash('info', 'Admin user already exists.');
return res.redirect(302, '/login');
}
} catch (error) {
console.error('Error in setup route:', error);
req.flash('error', 'An error occurred during setup. Please try again.');
return res.redirect(302, '/setup');
}
});
app.get('/login', (req, res) => {
res.render('login', {
listType: occasion[LIST_TYPE],
messages: {
error: req.flash('error'),
success: req.flash('success'),
info: req.flash('info')
}
});
});
app.post('/login', [
body('username').trim().escape(),
body('password').trim()
], (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) {
console.error('Error during authentication:', err);
return next(err);
}
if (!user) {
console.log('Authentication failed:', info.message);
req.flash('error', info.message);
return res.redirect('/login');
}
req.logIn(user, (err) => {
if (err) {
console.error('Error during login:', err);
return next(err);
}
console.log('User logged in successfully:', user.username);
return res.redirect('/admin');
});
})(req, res, next);
});
app.get('/logout', (req, res) => {
req.logout((err) => {
if (err) {
console.error('Logout error:', err);
}
res.redirect('/');
});
});
app.get('/admin', auth, async (req, res) => {
const items = await Item.find().sort({ _id: -1 });
res.render('admin', {
listType: occasion[LIST_TYPE],
currency: CURRENCY,
currencySymbol: currencySymbols[CURRENCY],
items: items
});
});
app.post('/admin/add-item', auth, [
body('name').trim().escape(),
body('price').isFloat({ min: 0, max: 1000000 }).toFloat(),
body('url').isURL().customSanitizer(value => {
if (!/^https?:\/\//i.test(value)) {
value = 'http://' + value;
}
return value;
}),
body('imageUrl').isURL().customSanitizer(value => {
if (!/^https?:\/\//i.test(value)) {
value = 'http://' + value;
}
return value;
})
], async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const { name, price, url, imageUrl } = req.body;
const sanitizedName = sanitizeHtml(name, {
allowedTags: [],
allowedAttributes: {}
});
try {
await Item.create({ name: sanitizedName, price, url, imageUrl, purchased: false });
res.redirect('/');
} catch (error) {
console.error('Error adding item:', error);
res.status(500).send('Error adding item');
}
});
app.post('/admin/delete-item/:id', auth, async (req, res) => {
try {
await Item.findByIdAndDelete(req.params.id);
res.redirect('/admin');
} catch (error) {
console.error('Error deleting item:', error);
res.status(500).send('Error deleting item');
}
});
app.get('/', async (req, res) => {
const wishlistItems = await Item.find({ purchased: false }).sort({ _id: -1 });
const purchasedItems = await Item.find({ purchased: true }).sort({ _id: -1 });
res.render('index', {
wishlistItems,
purchasedItems,
currency: CURRENCY,
currencySymbol: currencySymbols[CURRENCY],
listName: LIST_NAME,
listType: occasion[LIST_TYPE]
});
});
app.post('/purchase/:id', async (req, res) => {
try {
await Item.findByIdAndUpdate(req.params.id, { purchased: true });
res.redirect('/');
} catch (error) {
console.error('Error purchasing item:', error);
res.status(500).send('Error purchasing item');
}
});
app.post('/restore/:id', async (req, res) => {
try {
await Item.findByIdAndUpdate(req.params.id, { purchased: false });
res.redirect('/');
} catch (error) {
console.error('Error restoring item:', error);
res.status(500).send('Error restoring item');
}
});
app.listen(PORT, () => {
console.log(`Server running on http://localhost:${PORT}`);
});