-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
389 lines (317 loc) · 11.4 KB
/
index.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
// -- Imports -- //
var http = require('http');
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var MongoStore = require('connect-mongo')(session);
var crypto = require('crypto');
// -- Repositories -- //
var userRepository = require('./repositories/userRepository');
var productRepository = require('./repositories/productRepository');
var orderRepository = require('./repositories/orderRepository');
// -- Setup -- //
var mongoUrl = 'mongodb://heroku_wfqz3rhs:[email protected]:17199/heroku_wfqz3rhs';
var secretString = '2a6f51a3513b4cb8b7087faffdef27d0';
var app = express();
app.set('view engine', 'ejs');
app.set('views', './views');
app.use(cookieParser(secretString));
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: secretString,
store: new MongoStore({ url: mongoUrl }),
resave: false,
saveUninitialized: true,
cookie: { maxAge: 1000*60*60 }
}));
app.use(express.static('./static'));
// -- Helpers -- //
var appendMeta = (req, model) => {
var cookie = req.signedCookies.authcookie;
if (cookie) {
model.user = { login : cookie.login, role : cookie.role };
}
if (req.session.msg) {
model.message = req.session.msg;
delete req.session['msg'];
}
return model;
}
// -- Views -- //
app.get('/', (req, res) => {
var model = appendMeta (req, { products : {} });
productRepository.findAll().then(prods => {
model.products = prods;
res.render('products', model);
}).catch((err) => {
model.message = `Zapytanie do bazy danych zawiodło. (${err})`;
res.render('products', model);
});
});
app.get('/add_product', authorizeAdmin, (req, res) => {
var model = appendMeta(req, {})
res.render('add_product', model)
})
app.post('/add_product', authorizeAdmin, (req, res) => {
var name = req.body.name;
var description = req.body.description;
var price = Number.parseInt(req.body.price);
var img = req.body.img;
productRepository.add(name, price, description, img).then(() => {
req.session.msg = `Pomyślnie dodano produkt ${name}.`;
res.redirect('/admin');
}).catch(() => {
req.session.msg = `Zapytanie do bazy danych zawiodło. (${err})`;
res.redirect('/add_product');
})
})
app.get('/edit_product/:id', authorizeAdmin, (req, res) => {
var model = appendMeta(req, {});
model.id = req.params.id;
productRepository.findById(model.id).then((product) => {
model.name = product.name;
model.description = product.description;
model.price = product.price;
model.img = product.img;
res.render('edit_product', model);
}).catch((err) => {
req.session.msg = `Nie znalazłem produktu o takim ID. (${err})`;
res.redirect('/admin');
})
})
app.post('/edit_product', authorizeAdmin, (req, res) => {
var name = req.body.name;
var description = req.body.description;
var price = Number.parseInt(req.body.price);
var id = req.body.id;
var img = req.body.img;
productRepository.edit(id, name, price, description, img).then(() => {
req.session.msg = `Pomyślnie edytowano produkt ${name}.`
res.redirect('/admin')
}).catch((err) => {
req.session.msg = `Zapytanie do bazy danych zawiodło. (${err})`;
res.redirect('/admin');
})
})
app.get('/delete_product/:id', authorizeAdmin, (req, res) => {
productRepository.delete(req.params.id).then(() => {
req.session.msg = 'Usunięto produkt.'
res.redirect('/admin')
}).catch((err) => {
req.session.msg = `Zapytanie do bazy danych zawiodło. (${err})`
res.redirect('/admin')
})
})
app.get('/login', (req, res) => {
if (req.signedCookies.authcookie) {
res.redirect('/');
} else {
if (req.query.returnUrl) {
req.session.returnUrl = req.query.returnUrl;
}
res.render('login');
}
});
app.post('/login', (req, res) => {
var login = req.body.login;
var password = req.body.password;
userRepository.findByLogin(login).then((user) => {
var returnUrl;
if (req.session.returnUrl) {
returnUrl = JSON.parse(JSON.stringify(req.session.returnUrl));
delete req.session.returnUrl;
} else {
returnUrl = '/';
}
sha256 = crypto.createHash('sha256');
sha256.update(password);
hashedPassword = sha256.digest('hex');
if (user && user.password == hashedPassword) {
res.cookie('authcookie', {login: login, role: user.role}, {signed: true, maxAge: 1000 * 60 * 60})
req.session.msg = 'Logowanie pomyślne.'
res.redirect(returnUrl)
} else {
res.render('login', {message: 'Zły login lub hasło.'});
}
}).catch((err) => {
res.render('login', {message: `Zapytanie do bazy danych zawiodło. (${err})`});
})
});
app.get('/register', (req, res) => {
if (req.signedCookies.authcookie) {
res.redirect('/');
}
res.render('register', appendMeta(req, {}));
});
app.get('/logout', (req, res) => {
if (req.signedCookies.authcookie) {
res.cookie('authcookie', {}, {signed: true, maxAge: -1});
req.session.cart = {}
req.session.msg = 'Wylogowano.'
}
res.redirect('/');
});
app.post('/register', (req, res) => {
var login = req.body.login;
var password = req.body.password;
var model = appendMeta(req, {});
userRepository.findByLogin(login).then((user) => {
if (user != null) {
model.message = 'Użytkownik o takim loginie już istnieje.';
res.render('register', model);
} else {
sha256 = crypto.createHash('sha256');
sha256.update(password);
hashedPassword = sha256.digest('hex');
userRepository.add(login, hashedPassword).then(() => {
model.message = 'Pomyślnie utworzono konto.';
res.render('login', model);
}).catch((err) => {
model.message = `Zapytanie do bazy danych zawiodło. (${err})`;
res.render('register', model);
});
}
}).catch((err) => {
model.message = `Zapytanie do bazy danych zawiodło. (${err})`;
res.render('register', model);
});
});
app.post('/search', (req, res) => {
var srch = req.body.search_field.toLowerCase();
var model = appendMeta (req, { products : {} });
productRepository.findAll().then(prods => {
model.products = prods.filter(prod =>
prod.name.toLowerCase().indexOf(srch) > -1 ||
prod.description.toLowerCase().indexOf(srch) > -1);
res.render('products', model);
}).catch((err) => {
model.message = `Zapytanie do bazy danych zawiodło. (${err})`;
res.render('products', model);
});
});
app.get('/cart', authorizeUser, (req, res) => {
if (!req.session.cart)
req.session.cart = {};
productRepository.findAll().then(prods => {
var total = 0;
var cart_products = Object.keys(req.session.cart).map(key => {
var cnt = req.session.cart[key];
var prod = prods.find(prod => prod._id == key);
prod.quantity = cnt;
total += cnt * Number.parseInt(prod.price);
return prod;
});
var model = appendMeta(req, { products: cart_products, total : total });
res.render('cart', model);
}).catch((err) => {
req.session.msg = `Zapytanie do bazy danych zawiodło. (${err})`;
res.redirect('/');
});
})
app.get('/checkout', authorizeUser, (req, res) => {
if (!req.session.cart || Object.keys(req.session.cart).length === 0) {
req.session.msg = 'Koszyk jest pusty!';
res.redirect('/');
} else {
orderRepository.add(req.session.login, req.session.cart).then(() => {
req.session.cart = {};
req.session.msg = 'Zamówienie zostało złożone. Dziękujemy za zakupy!';
res.redirect('/');
}).catch((err) => {
req.session.msg = `Zapytanie do bazy danych zawiodło. (${err})`;
res.redirect('/');
})
}
});
app.get('/add_to_cart/:id', authorizeUser, (req, res) => {
if (!req.session.cart)
req.session.cart = {};
req.session.login = req.signedCookies.authcookie.login
var id = req.params.id;
productRepository.findAll().then(prods => {
var product = prods.find(prod => prod._id == id);
if (product) {
if (!req.session.cart[id])
req.session.cart[id] = 1;
else
req.session.cart[id] += 1;
req.session.msg = `Dodano ${product.name} do koszyka.`;
res.redirect('/');
}
}).catch((err) => {
req.session.msg = `Zapytanie do bazy danych zawiodło. (${err})`;
res.redirect('/');
})
});
app.get('/remove_from_cart/:id/:name', authorizeUser, (req, res) => {
if (!req.session.cart)
req.session.cart = {};
var id = req.params.id;
delete req.session.cart[id];
var name = req.params.name;
req.session.msg = `Usunięto ${name} z koszyka.`;
res.redirect('/cart');
});
var changeIdsToProductNames = function (products, orders) {
var result = []
orders.forEach((order) => {
result.push({login: order.login, cart: {}})
Object.keys(order.cart).forEach((key) => {
var product = products.find(p => p._id == key)
var productName
if (!product) {
productName = '[produkt usunięty]'
} else {
productName = product.name
}
result[result.length - 1].cart[productName] = order.cart[key]
})
})
return result
}
app.get('/admin', authorizeAdmin, (req, res) => {
var model = appendMeta(req, {})
userRepository.findAll().then((users) => {
model.users = users;
productRepository.findAll().then((products) => {
model.products = products;
orderRepository.findAllPlaced().then((placedOrders) => {
model.placedOrders = changeIdsToProductNames(products, placedOrders)
orderRepository.findAllPending().then((pendingOrders) => {
model.pendingOrders = changeIdsToProductNames(products, pendingOrders)
res.render('admin', model);
})
})
})
}).catch((err) => {
model.message(`Zapytanie do bazy danych zawiodło. (${err})`)
res.render('admin', model);
})
})
// -- Auth functions -- //
function authorizeUser(req, res, next) {
if (!req.signedCookies.authcookie) {
res.redirect('/login?returnUrl=' + req.url);
} else {
next();
}
}
function authorizeAdmin(req, res, next) {
if (!req.signedCookies.authcookie) {
res.redirect('/login?returnUrl=' + req.url);
} else if (req.signedCookies.authcookie.role !== 'admin') {
req.session.msg = 'Brak uprawnień.'
res.redirect('/')
} else {
next();
}
}
// -- 404 -- //
app.use((req, res, next) => {
var model = appendMeta(req, {});
res.render('404', model);
});
// -- http server -- //
var server = http.createServer(app).listen(process.env.PORT || 3000);
console.log('server started');