-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
370 lines (342 loc) · 11.1 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
const express = require('express');
const path = require('path');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const session = require('express-session');
const moment = require('moment');
const MongoStore = require('connect-mongodb-session')(session);
const MongoClient = require('mongodb').MongoClient;
const numeral = require('numeral');
const helmet = require('helmet');
const colors = require('colors');
const common = require('./lib/common');
const mongodbUri = require('mongodb-uri');
let handlebars = require('express-handlebars');
// Validate our settings schema
const Ajv = require('ajv');
const ajv = new Ajv({useDefaults: true});
const baseConfig = ajv.validate(require('./config/baseSchema'), require('./config/settings.json'));
if(baseConfig === false){
console.log(colors.red(`settings.json incorrect: ${ajv.errorsText()}`));
process.exit(2);
}
// get config
let config = common.getConfig();
// Validate the payment gateway config
if(config.paymentGateway === 'paypal'){
const paypalConfig = ajv.validate(require('./config/paypalSchema'), require('./config/paypal.json'));
if(paypalConfig === false){
console.log(colors.red(`PayPal config is incorrect: ${ajv.errorsText()}`));
process.exit(2);
}
}
if(config.paymentGateway === 'stripe'){
const stripeConfig = ajv.validate(require('./config/stripeSchema'), require('./config/stripe.json'));
if(stripeConfig === false){
console.log(colors.red(`Stripe config is incorrect: ${ajv.errorsText()}`));
process.exit(2);
}
}
if(config.paymentGateway === 'authorizenet'){
const authorizenetConfig = ajv.validate(require('./config/authorizenetSchema'), require('./config/authorizenet.json'));
if(authorizenetConfig === false){
console.log(colors.red(`Authorizenet config is incorrect: ${ajv.errorsText()}`));
process.exit(2);
}
}
// require the routes
const index = require('./routes/index');
const admin = require('./routes/admin');
const product = require('./routes/product');
const customer = require('./routes/customer');
const order = require('./routes/order');
const user = require('./routes/user');
const paypal = require('./routes/payments/paypal');
const stripe = require('./routes/payments/stripe');
const authorizenet = require('./routes/payments/authorizenet');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, '/views'));
app.engine('hbs', handlebars({
extname: 'hbs',
layoutsDir: path.join(__dirname, 'views', 'layouts'),
defaultLayout: 'layout.hbs',
partialsDir: [ path.join(__dirname, 'views') ]
}));
app.set('view engine', 'hbs');
// helpers for the handlebar templating platform
handlebars = handlebars.create({
helpers: {
perRowClass: function(numProducts){
if(parseInt(numProducts) === 1){
return'col-md-12 col-xl-12 col m12 xl12 product-item';
}
if(parseInt(numProducts) === 2){
return'col-md-6 col-xl-6 col m6 xl6 product-item';
}
if(parseInt(numProducts) === 3){
return'col-md-4 col-xl-4 col m4 xl4 product-item';
}
if(parseInt(numProducts) === 4){
return'col-md-3 col-xl-3 col m3 xl3 product-item';
}
return'col-md-6 col-xl-6 col m6 xl6 product-item';
},
menuMatch: function(title, search){
if(!title || !search){
return'';
}
if(title.toLowerCase().startsWith(search.toLowerCase())){
return'class="navActive"';
}
return'';
},
getTheme: function(view){
return`themes/${config.theme}/${view}`;
},
formatAmount: function(amt){
if(amt){
return numeral(amt).format('0.00');
}
return'0.00';
},
amountNoDecimal: function(amt){
if(amt){
return handlebars.helpers.formatAmount(amt).replace('.', '');
}
return handlebars.helpers.formatAmount(amt);
},
getStatusColor: function (status){
switch(status){
case'Paid':
return'success';
case'Approved':
return'success';
case'Approved - Processing':
return'success';
case'Failed':
return'danger';
case'Completed':
return'success';
case'Shipped':
return'success';
case'Pending':
return'warning';
default:
return'danger';
}
},
checkProductOptions: function (opts){
if(opts){
return'true';
}
return'false';
},
currencySymbol: function(value){
if(typeof value === 'undefined' || value === ''){
return'$';
}
return value;
},
objectLength: function(obj){
if(obj){
return Object.keys(obj).length;
}
return 0;
},
checkedState: function (state){
if(state === 'true' || state === true){
return'checked';
}
return'';
},
selectState: function (state, value){
if(state === value){
return'selected';
}
return'';
},
isNull: function (value, options){
if(typeof value === 'undefined' || value === ''){
return options.fn(this);
}
return options.inverse(this);
},
toLower: function (value){
if(value){
return value.toLowerCase();
}
return null;
},
formatDate: function (date, format){
return moment(date).format(format);
},
ifCond: function (v1, operator, v2, options){
switch(operator){
case'==':
return(v1 === v2) ? options.fn(this) : options.inverse(this);
case'!=':
return(v1 !== v2) ? options.fn(this) : options.inverse(this);
case'===':
return(v1 === v2) ? options.fn(this) : options.inverse(this);
case'<':
return(v1 < v2) ? options.fn(this) : options.inverse(this);
case'<=':
return(v1 <= v2) ? options.fn(this) : options.inverse(this);
case'>':
return(v1 > v2) ? options.fn(this) : options.inverse(this);
case'>=':
return(v1 >= v2) ? options.fn(this) : options.inverse(this);
case'&&':
return(v1 && v2) ? options.fn(this) : options.inverse(this);
case'||':
return(v1 || v2) ? options.fn(this) : options.inverse(this);
default:
return options.inverse(this);
}
},
isAnAdmin: function (value, options){
if(value === 'true' || value === true){
return options.fn(this);
}
return options.inverse(this);
}
}
});
// session store
let store = new MongoStore({
uri: config.databaseConnectionString,
collection: 'sessions'
});
app.enable('trust proxy');
app.use(helmet());
app.set('port', process.env.PORT || 1111);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser('5TOCyfH3HuszKGzFZntk'));
app.use(session({
resave: true,
saveUninitialized: true,
secret: 'pAgGxo8Hzg7PFlv1HpO8Eg0Y6xtP7zYx',
cookie: {
path: '/',
httpOnly: true,
maxAge: 3600000 * 24
},
store: store
}));
// serving static content
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'views', 'themes')));
// Make stuff accessible to our router
app.use((req, res, next) => {
req.handlebars = handlebars;
next();
});
// update config when modified
app.use((req, res, next) => {
next();
if(res.configDirty){
config = common.getConfig();
app.config = config;
}
});
// Ran on all routes
app.use((req, res, next) => {
res.setHeader('Cache-Control', 'no-cache, no-store');
next();
});
// setup the routes
app.use('/', index);
app.use('/', customer);
app.use('/', product);
app.use('/', order);
app.use('/', user);
app.use('/', admin);
app.use('/paypal', paypal);
app.use('/stripe', stripe);
app.use('/authorizenet', authorizenet);
// catch 404 and forward to error handler
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if(app.get('env') === 'development'){
app.use((err, req, res, next) => {
console.error(colors.red(err.stack));
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err,
helpers: handlebars.helpers
});
});
}
// production error handler
// no stacktraces leaked to user
app.use((err, req, res, next) => {
console.error(colors.red(err.stack));
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {},
helpers: handlebars.helpers
});
});
// Nodejs version check
const nodeVersionMajor = parseInt(process.version.split('.')[0].replace('v', ''));
if(nodeVersionMajor < 7){
console.log(colors.red(`Please use Node.js version 7.x or above. Current version: ${nodeVersionMajor}`));
process.exit(2);
}
app.on('uncaughtException', (err) => {
console.error(colors.red(err.stack));
process.exit(2);
});
MongoClient.connect(config.databaseConnectionString, {}, (err, client) => {
// On connection error we display then exit
if(err){
console.log(colors.red('Error connecting to MongoDB: ' + err));
process.exit(2);
}
// select DB
const dbUriObj = mongodbUri.parse(config.databaseConnectionString);
let db;
// if in testing, set the testing DB
if(process.env.NODE_ENV === 'test'){
db = client.db('testingdb');
}else{
db = client.db(dbUriObj.database);
}
// setup the collections
db.users = db.collection('users');
db.products = db.collection('products');
db.orders = db.collection('orders');
db.pages = db.collection('pages');
db.menu = db.collection('menu');
db.customers = db.collection('customers');
// add db to app for routes
app.dbClient = client;
app.db = db;
app.config = config;
app.port = app.get('port');
// run indexing
common.runIndexing(app)
.then(app.listen(app.get('port')))
.then(() => {
// lift the app
app.emit('appStarted');
console.log(colors.green('expressCart running on host: http://localhost:' + app.get('port')));
})
.catch((err) => {
console.error(colors.red('Error setting up indexes:' + err));
process.exit(2);
});
});
module.exports = app;