forked from gabrieleromanato/Node.js-Shopping-Cart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
178 lines (156 loc) · 4.82 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
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const port = process.env.PORT || 8080;
const mongoose = require('mongoose');
const helmet = require('helmet');
const path = require('path');
const favicon = require('serve-favicon');
const session = require('express-session');
const MongoDBStore = require('connect-mongodb-session')(session);
const app = express();
const config = require('./lib/config.js');
mongoose.Promise = Promise;
mongoose.connect(config.db.url, {
useMongoClient: true
});
const Products = require('./models/Products');
const Cart = require('./lib/Cart');
const Security = require('./lib/Security');
const store = new MongoDBStore({
uri: config.db.url,
collection: config.db.sessions
});
app.disable('x-powered-by');
app.set('view engine', 'ejs');
app.set('env', 'development');
app.locals.paypal = config.paypal;
app.locals.locale = config.locale;
app.use(favicon(path.join(__dirname, 'favicon.png')));
app.use('/public', express.static(path.join(__dirname, '/public'), {
maxAge: 0,
dotfiles: 'ignore',
etag: false
}));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(helmet());
app.use(session({
secret: config.secret,
resave: false,
saveUninitialized: true,
unset: 'destroy',
store: store,
name: config.name + '-' + Security.generateId(),
genid: (req) => {
return Security.generateId()
}
}));
app.get('/', (req, res) => {
if(!req.session.cart) {
req.session.cart = {
items: [],
totals: 0.00,
formattedTotals: ''
};
}
Products.find({price: {'$gt': 0}}).sort({price: -1}).limit(6).then(products => {
let format = new Intl.NumberFormat(req.app.locals.locale.lang, {style: 'currency', currency: req.app.locals.locale.currency });
products.forEach( (product) => {
product.formattedPrice = format.format(product.price);
});
res.render('index', {
pageTitle: 'Node.js Shopping Cart',
products: products,
nonce: Security.md5(req.sessionID + req.headers['user-agent'])
});
}).catch(err => {
res.status(400).send('Bad request');
});
});
app.get('/cart', (req, res) => {
let sess = req.session;
let cart = (typeof sess.cart !== 'undefined') ? sess.cart : false;
res.render('cart', {
pageTitle: 'Cart',
cart: cart,
nonce: Security.md5(req.sessionID + req.headers['user-agent'])
});
});
app.get('/cart/remove/:id/:nonce', (req, res) => {
let id = req.params.id;
if(/^\d+$/.test(id) && Security.isValidNonce(req.params.nonce, req)) {
Cart.removeFromCart(parseInt(id, 10), req.session.cart);
res.redirect('/cart');
} else {
res.redirect('/');
}
});
app.get('/cart/empty/:nonce', (req, res) => {
if(Security.isValidNonce(req.params.nonce, req)) {
Cart.emptyCart(req);
res.redirect('/cart');
} else {
res.redirect('/');
}
});
app.post('/cart', (req, res) => {
let qty = parseInt(req.body.qty, 10);
let product = parseInt(req.body.product_id, 10);
if(qty > 0 && Security.isValidNonce(req.body.nonce, req)) {
Products.findOne({product_id: product}).then(prod => {
let cart = (req.session.cart) ? req.session.cart : null;
Cart.addToCart(prod, qty, cart);
res.redirect('/cart');
}).catch(err => {
res.redirect('/');
});
} else {
res.redirect('/');
}
});
app.post('/cart/update', (req, res) => {
let ids = req.body["product_id[]"];
let qtys = req.body["qty[]"];
if(Security.isValidNonce(req.body.nonce, req)) {
let cart = (req.session.cart) ? req.session.cart : null;
let i = (!Array.isArray(ids)) ? [ids] : ids;
let q = (!Array.isArray(qtys)) ? [qtys] : qtys;
Cart.updateCart(i, q, cart);
res.redirect('/cart');
} else {
res.redirect('/');
}
});
app.get('/checkout', (req, res) => {
let sess = req.session;
let cart = (typeof sess.cart !== 'undefined') ? sess.cart : false;
res.render('checkout', {
pageTitle: 'Checkout',
cart: cart,
checkoutDone: false,
nonce: Security.md5(req.sessionID + req.headers['user-agent'])
});
});
app.post('/checkout', (req, res) => {
let sess = req.session;
let cart = (typeof sess.cart !== 'undefined') ? sess.cart : false;
if(Security.isValidNonce(req.body.nonce, req)) {
res.render('checkout', {
pageTitle: 'Checkout',
cart: cart,
checkoutDone: true
});
} else {
res.redirect('/');
}
});
if (app.get('env') === 'development') {
app.use((err, req, res, next) => {
res.status(err.status || 500);
});
}
app.use((err, req, res, next) => {
res.status(err.status || 500);
});
app.listen(port);