Linting and refactoring

master
Mark Moffat 2019-06-15 14:16:08 +09:30
parent 83f5c1f159
commit 291a044d0b
15 changed files with 501 additions and 446 deletions

View File

@ -17,7 +17,7 @@
}, },
"rules": { "rules": {
"quotes": ["error", "single"], "quotes": ["error", "single"],
"prefer-arrow-callback": 2, "prefer-arrow-callback": [ "error", { "allowNamedFunctions": true } ],
"consistent-return": 2, "consistent-return": 2,
"no-var" : 2, "no-var" : 2,
"new-cap" : 0, "new-cap" : 0,
@ -27,11 +27,16 @@
"space-unary-ops" : 2, "space-unary-ops" : 2,
"no-undef": 1, "no-undef": 1,
"no-unused-vars": 1, "no-unused-vars": 1,
"keyword-spacing": ["error", { "before": false, "after": false }], "keyword-spacing": [
"error", {
"before": false, "after": false, "overrides": {
"const": { "after": true }
}
}],
"space-before-function-paren": 0, "space-before-function-paren": 0,
"space-before-blocks": ["error", "never"], "space-before-blocks": ["error", "never"],
"camelcase": 0, "camelcase": 0,
"handle-callback-err": ["error", "none"], "handle-callback-err": ["error", "none"],
"object-curly-spacing": ["error", "never"] "object-curly-spacing": ["error", "always"]
} }
} }

11
app.js
View File

@ -12,12 +12,13 @@ const helmet = require('helmet');
const colors = require('colors'); const colors = require('colors');
const cron = require('node-cron'); const cron = require('node-cron');
const common = require('./lib/common'); const common = require('./lib/common');
const{initDb} = require('./lib/db'); const { runIndexing } = require('./lib/indexing');
const { initDb } = require('./lib/db');
let handlebars = require('express-handlebars'); let handlebars = require('express-handlebars');
// Validate our settings schema // Validate our settings schema
const Ajv = require('ajv'); const Ajv = require('ajv');
const ajv = new Ajv({useDefaults: true}); const ajv = new Ajv({ useDefaults: true });
const baseConfig = ajv.validate(require('./config/baseSchema'), require('./config/settings.json')); const baseConfig = ajv.validate(require('./config/baseSchema'), require('./config/settings.json'));
if(baseConfig === false){ if(baseConfig === false){
@ -226,7 +227,7 @@ app.use(helmet());
app.set('port', process.env.PORT || 1111); app.set('port', process.env.PORT || 1111);
app.use(logger('dev')); app.use(logger('dev'));
app.use(bodyParser.json()); app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('5TOCyfH3HuszKGzFZntk')); app.use(cookieParser('5TOCyfH3HuszKGzFZntk'));
app.use(session({ app.use(session({
resave: true, resave: true,
@ -345,7 +346,7 @@ initDb(config.databaseConnectionString, async (err, db) => {
// Remove any invalid cart holds // Remove any invalid cart holds
await db.cart.remove({ await db.cart.remove({
sessionId: {$nin: validSessionIds} sessionId: { $nin: validSessionIds }
}); });
}); });
@ -357,7 +358,7 @@ initDb(config.databaseConnectionString, async (err, db) => {
// We index when not in test env // We index when not in test env
if(process.env.NODE_ENV !== 'test'){ if(process.env.NODE_ENV !== 'test'){
try{ try{
await common.runIndexing(app); await runIndexing(app);
}catch(ex){ }catch(ex){
console.error(colors.red('Error setting up indexes:' + err)); console.error(colors.red('Error setting up indexes:' + err));
} }

92
lib/auth.js Normal file
View File

@ -0,0 +1,92 @@
const ObjectId = require('mongodb').ObjectID;
const _ = require('lodash');
const restrictedRoutes = [
{ route: '/admin/product/new', response: 'redirect' },
{ route: '/admin/product/insert', response: 'redirect' },
{ route: '/admin/product/edit/:id', response: 'redirect' },
{ route: '/admin/product/update', response: 'redirect' },
{ route: '/admin/product/delete/:id', response: 'redirect' },
{ route: '/admin/product/published_state', response: 'json' },
{ route: '/admin/product/setasmainimage', response: 'json' },
{ route: '/admin/product/deleteimage', response: 'json' },
{ route: '/admin/order/statusupdate', response: 'json' },
{ route: '/admin/settings/update', response: 'json' },
{ route: '/admin/settings/option/remove', response: 'json' },
{ route: '/admin/settings/pages/new', response: 'redirect' },
{ route: '/admin/settings/pages/edit/:page', response: 'redirect' },
{ route: '/admin/settings/pages/update', response: 'json' },
{ route: '/admin/settings/pages/delete/:page', response: 'redirect' },
{ route: '/admin/settings/menu/new', response: 'redirect' },
{ route: '/admin/settings/menu/update', response: 'redirect' },
{ route: '/admin/settings/menu/delete/:menuid', response: 'redirect' },
{ route: '/admin/settings/menu/save_order', response: 'json' },
{ route: '/admin/file/upload', response: 'redirect' },
{ route: '/admin/file/delete', response: 'json' }
];
const restrict = (req, res, next) => {
checkLogin(req, res, next);
};
const checkLogin = async (req, res, next) => {
const db = req.app.db;
// if not protecting we check for public pages and don't checkLogin
if(req.session.needsSetup === true){
res.redirect('/admin/setup');
return;
}
// If API key, check for a user
if(req.headers.apikey){
try{
const user = await db.users.findOne({
apiKey: ObjectId(req.headers.apikey),
isAdmin: true
});
if(!user){
res.status(400).json({ message: 'Access denied' });
return;
}
// Set API authenticated in the req
req.apiAuthenticated = true;
next();
return;
}catch(ex){
res.status(400).json({ message: 'Access denied' });
return;
}
}
if(req.session.user){
next();
return;
}
res.redirect('/admin/login');
};
// Middleware to check for admin access for certain route
const checkAccess = (req, res, next) => {
const routeCheck = _.find(restrictedRoutes, { 'route': req.route.path });
// If the user is not an admin and route is restricted, show message and redirect to /admin
if(req.session.isAdmin === false && routeCheck){
if(routeCheck.response === 'redirect'){
req.session.message = 'Unauthorised. Please refer to administrator.';
req.session.messageType = 'danger';
res.redirect('/admin');
return;
}
if(routeCheck.response === 'json'){
res.status(400).json({ message: 'Unauthorised. Please refer to administrator.' });
}
}else{
next();
}
};
module.exports = {
restrict,
checkLogin,
checkAccess
};

View File

@ -1,7 +1,6 @@
const _ = require('lodash'); const _ = require('lodash');
const uglifycss = require('uglifycss'); const uglifycss = require('uglifycss');
const colors = require('colors'); const colors = require('colors');
const lunr = require('lunr');
const cheerio = require('cheerio'); const cheerio = require('cheerio');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@ -11,34 +10,10 @@ const nodemailer = require('nodemailer');
const sanitizeHtml = require('sanitize-html'); const sanitizeHtml = require('sanitize-html');
const escape = require('html-entities').AllHtmlEntities; const escape = require('html-entities').AllHtmlEntities;
const mkdirp = require('mkdirp'); const mkdirp = require('mkdirp');
let ObjectId = require('mongodb').ObjectID; const ObjectId = require('mongodb').ObjectID;
const restrictedRoutes = [
{route: '/admin/product/new', response: 'redirect'},
{route: '/admin/product/insert', response: 'redirect'},
{route: '/admin/product/edit/:id', response: 'redirect'},
{route: '/admin/product/update', response: 'redirect'},
{route: '/admin/product/delete/:id', response: 'redirect'},
{route: '/admin/product/published_state', response: 'json'},
{route: '/admin/product/setasmainimage', response: 'json'},
{route: '/admin/product/deleteimage', response: 'json'},
{route: '/admin/order/statusupdate', response: 'json'},
{route: '/admin/settings/update', response: 'json'},
{route: '/admin/settings/option/remove', response: 'json'},
{route: '/admin/settings/pages/new', response: 'redirect'},
{route: '/admin/settings/pages/edit/:page', response: 'redirect'},
{route: '/admin/settings/pages/update', response: 'json'},
{route: '/admin/settings/pages/delete/:page', response: 'redirect'},
{route: '/admin/settings/menu/new', response: 'redirect'},
{route: '/admin/settings/menu/update', response: 'redirect'},
{route: '/admin/settings/menu/delete/:menuid', response: 'redirect'},
{route: '/admin/settings/menu/save_order', response: 'json'},
{route: '/admin/file/upload', response: 'redirect'},
{route: '/admin/file/delete', response: 'json'}
];
// Allowed mime types for product images // Allowed mime types for product images
exports.allowedMimeType = [ const allowedMimeType = [
'image/jpeg', 'image/jpeg',
'image/png', 'image/png',
'image/gif', 'image/gif',
@ -46,54 +21,14 @@ exports.allowedMimeType = [
'image/webp' 'image/webp'
]; ];
exports.fileSizeLimit = 10485760; const fileSizeLimit = 10485760;
// common functions // common functions
exports.restrict = (req, res, next) => { const cleanHtml = (html) => {
exports.checkLogin(req, res, next);
};
exports.checkLogin = async (req, res, next) => {
const db = req.app.db;
// if not protecting we check for public pages and don't checkLogin
if(req.session.needsSetup === true){
res.redirect('/admin/setup');
return;
}
// If API key, check for a user
if(req.headers.apikey){
try{
const user = await db.users.findOne({
apiKey: ObjectId(req.headers.apikey),
isAdmin: true
});
if(!user){
res.status(400).json({message: 'Access denied'});
return;
}
// Set API authenticated in the req
req.apiAuthenticated = true;
next();
return;
}catch(ex){
res.status(400).json({message: 'Access denied'});
return;
}
}
if(req.session.user){
next();
return;
}
res.redirect('/admin/login');
};
exports.cleanHtml = (html) => {
return sanitizeHtml(html); return sanitizeHtml(html);
}; };
exports.mongoSanitize = (param) => { const mongoSanitize = (param) => {
if(param instanceof Object){ if(param instanceof Object){
for(const key in param){ for(const key in param){
if(/^\$/.test(key)){ if(/^\$/.test(key)){
@ -104,34 +39,14 @@ exports.mongoSanitize = (param) => {
return param; return param;
}; };
exports.checkboxBool = (param) => { const checkboxBool = (param) => {
if(param && param === 'on'){ if(param && param === 'on'){
return true; return true;
} }
return false; return false;
}; };
// Middleware to check for admin access for certain route const showCartCloseBtn = (page) => {
exports.checkAccess = (req, res, next) => {
const routeCheck = _.find(restrictedRoutes, {'route': req.route.path});
// If the user is not an admin and route is restricted, show message and redirect to /admin
if(req.session.isAdmin === false && routeCheck){
if(routeCheck.response === 'redirect'){
req.session.message = 'Unauthorised. Please refer to administrator.';
req.session.messageType = 'danger';
res.redirect('/admin');
return;
}
if(routeCheck.response === 'json'){
res.status(400).json({message: 'Unauthorised. Please refer to administrator.'});
}
}else{
next();
}
};
exports.showCartCloseBtn = (page) => {
let showCartCloseButton = true; let showCartCloseButton = true;
if(page === 'checkout' || page === 'pay'){ if(page === 'checkout' || page === 'pay'){
showCartCloseButton = false; showCartCloseButton = false;
@ -141,13 +56,13 @@ exports.showCartCloseBtn = (page) => {
}; };
// adds products to sitemap.xml // adds products to sitemap.xml
exports.addSitemapProducts = (req, res, cb) => { const addSitemapProducts = (req, res, cb) => {
let db = req.app.db; let db = req.app.db;
let config = exports.getConfig(); let config = getConfig();
let hostname = config.baseUrl; let hostname = config.baseUrl;
db.products.find({productPublished: 'true'}).toArray((err, products) => { db.products.find({ productPublished: 'true' }).toArray((err, products) => {
let posts = []; let posts = [];
if(err){ if(err){
cb(null, posts); cb(null, posts);
@ -169,7 +84,7 @@ exports.addSitemapProducts = (req, res, cb) => {
}); });
}; };
exports.clearSessionValue = (session, sessionVar) => { const clearSessionValue = (session, sessionVar) => {
let temp; let temp;
if(session){ if(session){
temp = session[sessionVar]; temp = session[sessionVar];
@ -178,8 +93,8 @@ exports.clearSessionValue = (session, sessionVar) => {
return temp; return temp;
}; };
exports.updateTotalCartAmount = (req, res) => { const updateTotalCartAmount = (req, res) => {
let config = exports.getConfig(); let config = getConfig();
req.session.totalCartAmount = 0; req.session.totalCartAmount = 0;
@ -196,7 +111,7 @@ exports.updateTotalCartAmount = (req, res) => {
} }
}; };
exports.checkDirectorySync = (directory) => { const checkDirectorySync = (directory) => {
try{ try{
fs.statSync(directory); fs.statSync(directory);
}catch(e){ }catch(e){
@ -208,20 +123,20 @@ exports.checkDirectorySync = (directory) => {
} }
}; };
exports.getThemes = () => { const getThemes = () => {
return fs.readdirSync(path.join(__dirname, '../', 'views', 'themes')).filter(file => fs.statSync(path.join(path.join(__dirname, '../', 'views', 'themes'), file)).isDirectory()); return fs.readdirSync(path.join(__dirname, '../', 'views', 'themes')).filter(file => fs.statSync(path.join(path.join(__dirname, '../', 'views', 'themes'), file)).isDirectory());
}; };
exports.getImages = (dir, req, res, callback) => { const getImages = (dir, req, res, callback) => {
let db = req.app.db; let db = req.app.db;
db.products.findOne({_id: exports.getId(dir)}, (err, product) => { db.products.findOne({ _id: getId(dir) }, (err, product) => {
if(err){ if(err){
console.error(colors.red('Error getting images', err)); console.error(colors.red('Error getting images', err));
} }
// loop files in /public/uploads/ // loop files in /public/uploads/
glob('public/uploads/' + product.productPermalink + '/**', {nosort: true}, (er, files) => { glob('public/uploads/' + product.productPermalink + '/**', { nosort: true }, (er, files) => {
// sort array // sort array
files.sort(); files.sort();
@ -249,7 +164,7 @@ exports.getImages = (dir, req, res, callback) => {
}); });
}; };
exports.getConfigFilename = () => { const getConfigFilename = () => {
let filename = path.join(__dirname, '../config', 'settings-local.json'); let filename = path.join(__dirname, '../config', 'settings-local.json');
if(fs.existsSync(filename)){ if(fs.existsSync(filename)){
return filename; return filename;
@ -257,8 +172,8 @@ exports.getConfigFilename = () => {
return path.join(__dirname, '../config', 'settings.json'); return path.join(__dirname, '../config', 'settings.json');
}; };
exports.getConfig = () => { const getConfig = () => {
let config = JSON.parse(fs.readFileSync(exports.getConfigFilename(), 'utf8')); let config = JSON.parse(fs.readFileSync(getConfigFilename(), 'utf8'));
config.customCss = typeof config.customCss !== 'undefined' ? escape.decode(config.customCss) : null; config.customCss = typeof config.customCss !== 'undefined' ? escape.decode(config.customCss) : null;
config.footerHtml = typeof config.footerHtml !== 'undefined' ? escape.decode(config.footerHtml) : null; config.footerHtml = typeof config.footerHtml !== 'undefined' ? escape.decode(config.footerHtml) : null;
config.googleAnalytics = typeof config.googleAnalytics !== 'undefined' ? escape.decode(config.googleAnalytics) : null; config.googleAnalytics = typeof config.googleAnalytics !== 'undefined' ? escape.decode(config.googleAnalytics) : null;
@ -283,8 +198,8 @@ exports.getConfig = () => {
return config; return config;
}; };
exports.getPaymentConfig = () => { const getPaymentConfig = () => {
let siteConfig = this.getConfig(); let siteConfig = getConfig();
const gateConfigFile = path.join(__dirname, '../config', `${siteConfig.paymentGateway}.json`); const gateConfigFile = path.join(__dirname, '../config', `${siteConfig.paymentGateway}.json`);
let config = []; let config = [];
@ -302,8 +217,8 @@ exports.getPaymentConfig = () => {
return config; return config;
}; };
exports.updateConfig = (fields) => { const updateConfig = (fields) => {
let settingsFile = exports.getConfig(); let settingsFile = getConfig();
_.forEach(fields, (value, key) => { _.forEach(fields, (value, key) => {
settingsFile[key] = value; settingsFile[key] = value;
@ -359,21 +274,21 @@ exports.updateConfig = (fields) => {
// write file // write file
try{ try{
fs.writeFileSync(exports.getConfigFilename(), JSON.stringify(settingsFile, null, 4)); fs.writeFileSync(getConfigFilename(), JSON.stringify(settingsFile, null, 4));
return true; return true;
}catch(exception){ }catch(exception){
return false; return false;
} }
}; };
exports.getMenu = (db) => { const getMenu = (db) => {
return db.menu.findOne({}); return db.menu.findOne({});
}; };
// creates a new menu item // creates a new menu item
exports.newMenu = (req, res) => { const newMenu = (req, res) => {
const db = req.app.db; const db = req.app.db;
return exports.getMenu(db) return getMenu(db)
.then((menu) => { .then((menu) => {
// if no menu present // if no menu present
if(!menu){ if(!menu){
@ -387,7 +302,7 @@ exports.newMenu = (req, res) => {
}; };
menu.items.push(newNav); menu.items.push(newNav);
return db.menu.updateOne({}, {$set: {items: menu.items}}, {upsert: true}) return db.menu.updateOne({}, { $set: { items: menu.items } }, { upsert: true })
.then(() => { .then(() => {
return true; return true;
}); });
@ -399,13 +314,13 @@ exports.newMenu = (req, res) => {
}; };
// delete a menu item // delete a menu item
exports.deleteMenu = (req, res, menuIndex) => { const deleteMenu = (req, res, menuIndex) => {
const db = req.app.db; const db = req.app.db;
return exports.getMenu(db) return getMenu(db)
.then((menu) => { .then((menu) => {
// Remove menu item // Remove menu item
menu.items.splice(menuIndex, 1); menu.items.splice(menuIndex, 1);
return db.menu.updateOne({}, {$set: {items: menu.items}}, {upsert: true}) return db.menu.updateOne({}, { $set: { items: menu.items } }, { upsert: true })
.then(() => { .then(() => {
return true; return true;
}); });
@ -416,15 +331,15 @@ exports.deleteMenu = (req, res, menuIndex) => {
}; };
// updates and existing menu item // updates and existing menu item
exports.updateMenu = (req, res) => { const updateMenu = (req, res) => {
const db = req.app.db; const db = req.app.db;
return exports.getMenu(db) return getMenu(db)
.then((menu) => { .then((menu) => {
// find menu item and update it // find menu item and update it
let menuIndex = _.findIndex(menu.items, ['title', req.body.navId]); let menuIndex = _.findIndex(menu.items, ['title', req.body.navId]);
menu.items[menuIndex].title = req.body.navMenu; menu.items[menuIndex].title = req.body.navMenu;
menu.items[menuIndex].link = req.body.navLink; menu.items[menuIndex].link = req.body.navLink;
return db.menu.updateOne({}, {$set: {items: menu.items}}, {upsert: true}) return db.menu.updateOne({}, { $set: { items: menu.items } }, { upsert: true })
.then(() => { .then(() => {
return true; return true;
}); });
@ -434,7 +349,7 @@ exports.updateMenu = (req, res) => {
}); });
}; };
exports.sortMenu = (menu) => { const sortMenu = (menu) => {
if(menu && menu.items){ if(menu && menu.items){
menu.items = _.sortBy(menu.items, 'order'); menu.items = _.sortBy(menu.items, 'order');
return menu; return menu;
@ -443,15 +358,15 @@ exports.sortMenu = (menu) => {
}; };
// orders the menu // orders the menu
exports.orderMenu = (req, res) => { const orderMenu = (req, res) => {
const db = req.app.db; const db = req.app.db;
return exports.getMenu(db) return getMenu(db)
.then((menu) => { .then((menu) => {
// update the order // update the order
for(let i = 0; i < req.body.navId.length; i++){ for(let i = 0; i < req.body.navId.length; i++){
_.find(menu.items, ['title', req.body.navId[i]]).order = i; _.find(menu.items, ['title', req.body.navId[i]]).order = i;
} }
return db.menu.updateOne({}, {$set: {items: menu.items}}, {upsert: true}) return db.menu.updateOne({}, { $set: { items: menu.items } }, { upsert: true })
.then(() => { .then(() => {
return true; return true;
}); });
@ -461,8 +376,8 @@ exports.orderMenu = (req, res) => {
}); });
}; };
exports.getEmailTemplate = (result) => { const getEmailTemplate = (result) => {
let config = this.getConfig(); let config = getConfig();
let template = fs.readFileSync(path.join(__dirname, '../public/email_template.html'), 'utf8'); let template = fs.readFileSync(path.join(__dirname, '../public/email_template.html'), 'utf8');
@ -480,8 +395,8 @@ exports.getEmailTemplate = (result) => {
return $.html(); return $.html();
}; };
exports.sendEmail = (to, subject, body) => { const sendEmail = (to, subject, body) => {
let config = this.getConfig(); let config = getConfig();
let emailSettings = { let emailSettings = {
host: config.emailHost, host: config.emailHost,
@ -495,7 +410,7 @@ exports.sendEmail = (to, subject, body) => {
// outlook needs this setting // outlook needs this setting
if(config.emailHost === 'smtp-mail.outlook.com'){ if(config.emailHost === 'smtp-mail.outlook.com'){
emailSettings.tls = {ciphers: 'SSLv3'}; emailSettings.tls = { ciphers: 'SSLv3' };
} }
let transporter = nodemailer.createTransport(emailSettings); let transporter = nodemailer.createTransport(emailSettings);
@ -516,7 +431,7 @@ exports.sendEmail = (to, subject, body) => {
}; };
// gets the correct type of index ID // gets the correct type of index ID
exports.getId = (id) => { const getId = (id) => {
if(id){ if(id){
if(id.length !== 24){ if(id.length !== 24){
return id; return id;
@ -525,9 +440,9 @@ exports.getId = (id) => {
return ObjectId(id); return ObjectId(id);
}; };
exports.getData = (req, page, query) => { const getData = (req, page, query) => {
let db = req.app.db; let db = req.app.db;
let config = exports.getConfig(); let config = getConfig();
let numberProducts = config.productsPerPage ? config.productsPerPage : 6; let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let skip = 0; let skip = 0;
@ -547,7 +462,7 @@ exports.getData = (req, page, query) => {
db.products.count(query) db.products.count(query)
]) ])
.then((result) => { .then((result) => {
const returnData = {data: result[0], totalProducts: result[1]}; const returnData = { data: result[0], totalProducts: result[1] };
return returnData; return returnData;
}) })
.catch((err) => { .catch((err) => {
@ -555,134 +470,31 @@ exports.getData = (req, page, query) => {
}); });
}; };
exports.indexProducts = (app) => { module.exports = {
// index all products in lunr on startup allowedMimeType,
return new Promise((resolve, reject) => { fileSizeLimit,
app.db.products.find({}).toArray((err, productsList) => { cleanHtml,
if(err){ mongoSanitize,
console.error(colors.red(err.stack)); checkboxBool,
reject(err); showCartCloseBtn,
} addSitemapProducts,
clearSessionValue,
// setup lunr indexing updateTotalCartAmount,
const productsIndex = lunr(function(){ checkDirectorySync,
this.field('productTitle', {boost: 10}); getThemes,
this.field('productTags', {boost: 5}); getImages,
this.field('productDescription'); getConfigFilename,
getConfig,
const lunrIndex = this; getPaymentConfig,
updateConfig,
// add to lunr index getMenu,
productsList.forEach((product) => { newMenu,
let doc = { deleteMenu,
'productTitle': product.productTitle, updateMenu,
'productTags': product.productTags, sortMenu,
'productDescription': product.productDescription, orderMenu,
'id': product._id getEmailTemplate,
}; sendEmail,
lunrIndex.add(doc); getId,
}); getData
});
app.productsIndex = productsIndex;
console.log(colors.cyan('- Product indexing complete'));
resolve();
});
});
};
exports.indexCustomers = (app) => {
// index all products in lunr on startup
return new Promise((resolve, reject) => {
app.db.customers.find({}).toArray((err, customerList) => {
if(err){
console.error(colors.red(err.stack));
reject(err);
}
// setup lunr indexing
const customersIndex = lunr(function(){
this.field('email', {boost: 10});
this.field('name', {boost: 5});
this.field('phone');
const lunrIndex = this;
// add to lunr index
customerList.forEach((customer) => {
let doc = {
'email': customer.email,
'name': `${customer.firstName} ${customer.lastName}`,
'phone': customer.phone,
'id': customer._id
};
lunrIndex.add(doc);
});
});
app.customersIndex = customersIndex;
console.log(colors.cyan('- Customer indexing complete'));
resolve();
});
});
};
exports.indexOrders = (app, cb) => {
// index all orders in lunr on startup
return new Promise((resolve, reject) => {
app.db.orders.find({}).toArray((err, ordersList) => {
if(err){
console.error(colors.red('Error setting up products index: ' + err));
reject(err);
}
// setup lunr indexing
const ordersIndex = lunr(function(){
this.field('orderEmail', {boost: 10});
this.field('orderLastname', {boost: 5});
this.field('orderPostcode');
const lunrIndex = this;
// add to lunr index
ordersList.forEach((order) => {
let doc = {
'orderLastname': order.orderLastname,
'orderEmail': order.orderEmail,
'orderPostcode': order.orderPostcode,
'id': order._id
};
lunrIndex.add(doc);
});
});
app.ordersIndex = ordersIndex;
console.log(colors.cyan('- Order indexing complete'));
resolve();
});
});
};
exports.fixProductDates = (products) => {
let index = 0;
products.forEach((product) => {
products[index].productAddedDate = new Date();
index++;
});
return products;
};
// start indexing products and orders
exports.runIndexing = (app) => {
console.info(colors.yellow('Setting up indexes..'));
return Promise.all([
exports.indexProducts(app),
exports.indexOrders(app),
exports.indexCustomers(app)
])
.catch((err) => {
console.info(colors.yellow('Error setting up indexes', err));
process.exit(2);
});
}; };

142
lib/indexing.js Normal file
View File

@ -0,0 +1,142 @@
const colors = require('colors');
const lunr = require('lunr');
const indexProducts = (app) => {
// index all products in lunr on startup
return new Promise((resolve, reject) => {
app.db.products.find({}).toArray((err, productsList) => {
if(err){
console.error(colors.red(err.stack));
reject(err);
}
// setup lunr indexing
const productsIndex = lunr(function(){
this.field('productTitle', { boost: 10 });
this.field('productTags', { boost: 5 });
this.field('productDescription');
const lunrIndex = this;
// add to lunr index
productsList.forEach((product) => {
let doc = {
'productTitle': product.productTitle,
'productTags': product.productTags,
'productDescription': product.productDescription,
'id': product._id
};
lunrIndex.add(doc);
});
});
app.productsIndex = productsIndex;
console.log(colors.cyan('- Product indexing complete'));
resolve();
});
});
};
const indexCustomers = (app) => {
// index all products in lunr on startup
return new Promise((resolve, reject) => {
app.db.customers.find({}).toArray((err, customerList) => {
if(err){
console.error(colors.red(err.stack));
reject(err);
}
// setup lunr indexing
const customersIndex = lunr(function(){
this.field('email', { boost: 10 });
this.field('name', { boost: 5 });
this.field('phone');
const lunrIndex = this;
// add to lunr index
customerList.forEach((customer) => {
let doc = {
'email': customer.email,
'name': `${customer.firstName} ${customer.lastName}`,
'phone': customer.phone,
'id': customer._id
};
lunrIndex.add(doc);
});
});
app.customersIndex = customersIndex;
console.log(colors.cyan('- Customer indexing complete'));
resolve();
});
});
};
const indexOrders = (app, cb) => {
// index all orders in lunr on startup
return new Promise((resolve, reject) => {
app.db.orders.find({}).toArray((err, ordersList) => {
if(err){
console.error(colors.red('Error setting up products index: ' + err));
reject(err);
}
// setup lunr indexing
const ordersIndex = lunr(function(){
this.field('orderEmail', { boost: 10 });
this.field('orderLastname', { boost: 5 });
this.field('orderPostcode');
const lunrIndex = this;
// add to lunr index
ordersList.forEach((order) => {
let doc = {
'orderLastname': order.orderLastname,
'orderEmail': order.orderEmail,
'orderPostcode': order.orderPostcode,
'id': order._id
};
lunrIndex.add(doc);
});
});
app.ordersIndex = ordersIndex;
console.log(colors.cyan('- Order indexing complete'));
resolve();
});
});
};
const fixProductDates = (products) => {
let index = 0;
products.forEach(() => {
products[index].productAddedDate = new Date();
index++;
});
return products;
};
// start indexing products and orders
const runIndexing = (app) => {
console.info(colors.yellow('Setting up indexes..'));
return Promise.all([
indexProducts(app),
indexOrders(app),
indexCustomers(app)
])
.catch((err) => {
console.info(colors.yellow('Error setting up indexes', err));
process.exit(2);
});
};
module.exports = {
indexProducts,
indexCustomers,
indexOrders,
fixProductDates,
runIndexing
};

View File

@ -1,5 +1,6 @@
const common = require('./common'); const { getConfig } = require('./common');
const{initDb} = require('./db'); const { initDb } = require('./db');
const { fixProductDates } = require('./indexing');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
@ -7,7 +8,7 @@ const testData = fs.readFileSync(path.join(__dirname, '..', 'bin', 'testdata.jso
const jsonData = JSON.parse(testData); const jsonData = JSON.parse(testData);
// get config // get config
let config = common.getConfig(); let config = getConfig();
initDb(config.databaseConnectionString, (err, db) => { initDb(config.databaseConnectionString, (err, db) => {
Promise.all([ Promise.all([
@ -20,7 +21,7 @@ initDb(config.databaseConnectionString, (err, db) => {
Promise.all([ Promise.all([
db.users.insertMany(jsonData.users), db.users.insertMany(jsonData.users),
db.customers.insertMany(jsonData.customers), db.customers.insertMany(jsonData.customers),
db.products.insertMany(common.fixProductDates(jsonData.products)), db.products.insertMany(fixProductDates(jsonData.products)),
db.menu.insertOne(jsonData.menu) db.menu.insertOne(jsonData.menu)
]) ])
.then(() => { .then(() => {

View File

@ -120,7 +120,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/admin/product/published_state', url: '/admin/product/published_state',
data: {id: this.id, state: this.checked} data: { id: this.id, state: this.checked }
}) })
.done(function(msg){ .done(function(msg){
showNotification(msg.message, 'success'); showNotification(msg.message, 'success');
@ -226,7 +226,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/admin/settings/option/remove/', url: '/admin/settings/option/remove/',
data: {productId: $('#frmProductId').val(), optName: name} data: { productId: $('#frmProductId').val(), optName: name }
}) })
.done(function(msg){ .done(function(msg){
showNotification(msg.message, 'success', true); showNotification(msg.message, 'success', true);
@ -467,7 +467,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/admin/order/statusupdate', url: '/admin/order/statusupdate',
data: {order_id: $('#order_id').val(), status: $('#orderStatus').val()} data: { order_id: $('#order_id').val(), status: $('#orderStatus').val() }
}) })
.done(function(msg){ .done(function(msg){
showNotification(msg.message, 'success', true); showNotification(msg.message, 'success', true);
@ -524,7 +524,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/product/addtocart', url: '/product/addtocart',
data: {productId: $(this).attr('data-id')} data: { productId: $(this).attr('data-id') }
}) })
.done(function(msg){ .done(function(msg){
$('#cart-count').text(msg.totalCartItems); $('#cart-count').text(msg.totalCartItems);
@ -567,7 +567,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/admin/product/setasmainimage', url: '/admin/product/setasmainimage',
data: {product_id: $('#frmProductId').val(), productImage: $(this).attr('data-id')} data: { product_id: $('#frmProductId').val(), productImage: $(this).attr('data-id') }
}) })
.done(function(msg){ .done(function(msg){
showNotification(msg.message, 'success', true); showNotification(msg.message, 'success', true);
@ -581,7 +581,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/admin/product/deleteimage', url: '/admin/product/deleteimage',
data: {product_id: $('#frmProductId').val(), productImage: $(this).attr('data-id')} data: { product_id: $('#frmProductId').val(), productImage: $(this).attr('data-id') }
}) })
.done(function(msg){ .done(function(msg){
showNotification(msg.message, 'success', true); showNotification(msg.message, 'success', true);
@ -597,7 +597,7 @@ $(document).ready(function (){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/admin/api/validate_permalink', url: '/admin/api/validate_permalink',
data: {'permalink': $('#frmProductPermalink').val(), 'docId': $('#frmProductId').val()} data: { 'permalink': $('#frmProductPermalink').val(), 'docId': $('#frmProductId').val() }
}) })
.done(function(msg){ .done(function(msg){
showNotification(msg, 'success'); showNotification(msg, 'success');
@ -677,7 +677,7 @@ function deleteFromCart(element){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/product/removefromcart', url: '/product/removefromcart',
data: {cartId: element.attr('data-id')} data: { cartId: element.attr('data-id') }
}) })
.done(function(msg){ .done(function(msg){
$('#cart-count').text(msg.totalCartItems); $('#cart-count').text(msg.totalCartItems);
@ -740,7 +740,7 @@ function updateCart(){
$.ajax({ $.ajax({
method: 'POST', method: 'POST',
url: '/product/updatecart', url: '/product/updatecart',
data: {items: JSON.stringify(cartItems)} data: { items: JSON.stringify(cartItems) }
}) })
.done(function(msg){ .done(function(msg){
// update cart items // update cart items
@ -758,7 +758,7 @@ function updateCartDiv(){
$.ajax({ $.ajax({
method: 'GET', method: 'GET',
url: '/cartPartial', url: '/cartPartial',
data: {path: path} data: { path: path }
}) })
.done(function(msg){ .done(function(msg){
// update cart div // update cart div

View File

@ -1,5 +1,6 @@
const express = require('express'); const express = require('express');
const common = require('../lib/common'); const common = require('../lib/common');
const { restrict, checkAccess } = require('../lib/auth');
const escape = require('html-entities').AllHtmlEntities; const escape = require('html-entities').AllHtmlEntities;
const colors = require('colors'); const colors = require('colors');
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
@ -12,7 +13,7 @@ const ObjectId = require('mongodb').ObjectID;
const router = express.Router(); const router = express.Router();
// Admin section // Admin section
router.get('/admin', common.restrict, (req, res, next) => { router.get('/admin', restrict, (req, res, next) => {
res.redirect('/admin/orders'); res.redirect('/admin/orders');
}); });
@ -59,15 +60,15 @@ router.get('/admin/login', (req, res) => {
router.post('/admin/login_action', (req, res) => { router.post('/admin/login_action', (req, res) => {
let db = req.app.db; let db = req.app.db;
db.users.findOne({userEmail: common.mongoSanitize(req.body.email)}, (err, user) => { db.users.findOne({ userEmail: common.mongoSanitize(req.body.email) }, (err, user) => {
if(err){ if(err){
res.status(400).json({message: 'A user with that email does not exist.'}); res.status(400).json({ message: 'A user with that email does not exist.' });
return; return;
} }
// check if user exists with that email // check if user exists with that email
if(user === undefined || user === null){ if(user === undefined || user === null){
res.status(400).json({message: 'A user with that email does not exist.'}); res.status(400).json({ message: 'A user with that email does not exist.' });
}else{ }else{
// we have a user under that email so we compare the password // we have a user under that email so we compare the password
bcrypt.compare(req.body.password, user.userPassword) bcrypt.compare(req.body.password, user.userPassword)
@ -77,10 +78,10 @@ router.post('/admin/login_action', (req, res) => {
req.session.usersName = user.usersName; req.session.usersName = user.usersName;
req.session.userId = user._id.toString(); req.session.userId = user._id.toString();
req.session.isAdmin = user.isAdmin; req.session.isAdmin = user.isAdmin;
res.status(200).json({message: 'Login successful'}); res.status(200).json({ message: 'Login successful' });
}else{ }else{
// password is not correct // password is not correct
res.status(400).json({message: 'Access denied. Check password and try again.'}); res.status(400).json({ message: 'Access denied. Check password and try again.' });
} }
}); });
} }
@ -152,7 +153,7 @@ router.post('/admin/setup_action', (req, res) => {
}); });
// settings update // settings update
router.get('/admin/settings', common.restrict, (req, res) => { router.get('/admin/settings', restrict, (req, res) => {
res.render('settings', { res.render('settings', {
title: 'Cart settings', title: 'Cart settings',
session: req.session, session: req.session,
@ -168,7 +169,7 @@ router.get('/admin/settings', common.restrict, (req, res) => {
}); });
// settings update // settings update
router.post('/admin/createApiKey', common.restrict, common.checkAccess, async (req, res) => { router.post('/admin/createApiKey', restrict, checkAccess, async (req, res) => {
const db = req.app.db; const db = req.app.db;
let result = await db.users.findOneAndUpdate({ let result = await db.users.findOneAndUpdate({
_id: ObjectId(req.session.userId), _id: ObjectId(req.session.userId),
@ -182,27 +183,27 @@ router.post('/admin/createApiKey', common.restrict, common.checkAccess, async (r
}); });
if(result.value && result.value.apiKey){ if(result.value && result.value.apiKey){
res.status(200).json({message: 'API Key generated', apiKey: result.value.apiKey}); res.status(200).json({ message: 'API Key generated', apiKey: result.value.apiKey });
return; return;
} }
res.status(400).json({message: 'Failed to generate API Key'}); res.status(400).json({ message: 'Failed to generate API Key' });
}); });
// settings update // settings update
router.post('/admin/settings/update', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/settings/update', restrict, checkAccess, (req, res) => {
let result = common.updateConfig(req.body); let result = common.updateConfig(req.body);
if(result === true){ if(result === true){
res.status(200).json({message: 'Settings successfully updated'}); res.status(200).json({ message: 'Settings successfully updated' });
res.configDirty = true; res.configDirty = true;
return; return;
} }
res.status(400).json({message: 'Permission denied'}); res.status(400).json({ message: 'Permission denied' });
}); });
// settings update // settings update
router.post('/admin/settings/option/remove', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/settings/option/remove', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.products.findOne({_id: common.getId(req.body.productId)}, (err, product) => { db.products.findOne({ _id: common.getId(req.body.productId) }, (err, product) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -210,24 +211,24 @@ router.post('/admin/settings/option/remove', common.restrict, common.checkAccess
let optJson = JSON.parse(product.productOptions); let optJson = JSON.parse(product.productOptions);
delete optJson[req.body.optName]; delete optJson[req.body.optName];
db.products.update({_id: common.getId(req.body.productId)}, {$set: {productOptions: JSON.stringify(optJson)}}, (err, numReplaced) => { db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productOptions: JSON.stringify(optJson) } }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
if(numReplaced.result.nModified === 1){ if(numReplaced.result.nModified === 1){
res.status(200).json({message: 'Option successfully removed'}); res.status(200).json({ message: 'Option successfully removed' });
}else{ }else{
res.status(400).json({message: 'Failed to remove option. Please try again.'}); res.status(400).json({ message: 'Failed to remove option. Please try again.' });
} }
}); });
}else{ }else{
res.status(400).json({message: 'Product not found. Try saving before removing.'}); res.status(400).json({ message: 'Product not found. Try saving before removing.' });
} }
}); });
}); });
// settings update // settings update
router.get('/admin/settings/menu', common.restrict, async (req, res) => { router.get('/admin/settings/menu', restrict, async (req, res) => {
const db = req.app.db; const db = req.app.db;
res.render('settings_menu', { res.render('settings_menu', {
title: 'Cart menu', title: 'Cart menu',
@ -242,7 +243,7 @@ router.get('/admin/settings/menu', common.restrict, async (req, res) => {
}); });
// settings page list // settings page list
router.get('/admin/settings/pages', common.restrict, (req, res) => { router.get('/admin/settings/pages', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.pages.find({}).toArray(async (err, pages) => { db.pages.find({}).toArray(async (err, pages) => {
if(err){ if(err){
@ -264,7 +265,7 @@ router.get('/admin/settings/pages', common.restrict, (req, res) => {
}); });
// settings pages new // settings pages new
router.get('/admin/settings/pages/new', common.restrict, common.checkAccess, async (req, res) => { router.get('/admin/settings/pages/new', restrict, checkAccess, async (req, res) => {
const db = req.app.db; const db = req.app.db;
res.render('settings_page_edit', { res.render('settings_page_edit', {
@ -281,9 +282,9 @@ router.get('/admin/settings/pages/new', common.restrict, common.checkAccess, asy
}); });
// settings pages editor // settings pages editor
router.get('/admin/settings/pages/edit/:page', common.restrict, common.checkAccess, (req, res) => { router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.pages.findOne({_id: common.getId(req.params.page)}, async (err, page) => { db.pages.findOne({ _id: common.getId(req.params.page) }, async (err, page) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -317,7 +318,7 @@ router.get('/admin/settings/pages/edit/:page', common.restrict, common.checkAcce
}); });
// settings update page // settings update page
router.post('/admin/settings/pages/update', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/settings/pages/update', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
let doc = { let doc = {
@ -329,37 +330,37 @@ router.post('/admin/settings/pages/update', common.restrict, common.checkAccess,
if(req.body.page_id){ if(req.body.page_id){
// existing page // existing page
db.pages.findOne({_id: common.getId(req.body.page_id)}, (err, page) => { db.pages.findOne({ _id: common.getId(req.body.page_id) }, (err, page) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
if(page){ if(page){
db.pages.update({_id: common.getId(req.body.page_id)}, {$set: doc}, {}, (err, numReplaced) => { db.pages.update({ _id: common.getId(req.body.page_id) }, { $set: doc }, {}, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
res.status(200).json({message: 'Page updated successfully', page_id: req.body.page_id}); res.status(200).json({ message: 'Page updated successfully', page_id: req.body.page_id });
}); });
}else{ }else{
res.status(400).json({message: 'Page not found'}); res.status(400).json({ message: 'Page not found' });
} }
}); });
}else{ }else{
// insert page // insert page
db.pages.insert(doc, (err, newDoc) => { db.pages.insert(doc, (err, newDoc) => {
if(err){ if(err){
res.status(400).json({message: 'Error creating page. Please try again.'}); res.status(400).json({ message: 'Error creating page. Please try again.' });
}else{ }else{
res.status(200).json({message: 'New page successfully created', page_id: newDoc._id}); res.status(200).json({ message: 'New page successfully created', page_id: newDoc._id });
} }
}); });
} }
}); });
// settings delete page // settings delete page
router.get('/admin/settings/pages/delete/:page', common.restrict, common.checkAccess, (req, res) => { router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.pages.remove({_id: common.getId(req.params.page)}, {}, (err, numRemoved) => { db.pages.remove({ _id: common.getId(req.params.page) }, {}, (err, numRemoved) => {
if(err){ if(err){
req.session.message = 'Error deleting page. Please try again.'; req.session.message = 'Error deleting page. Please try again.';
req.session.messageType = 'danger'; req.session.messageType = 'danger';
@ -373,7 +374,7 @@ router.get('/admin/settings/pages/delete/:page', common.restrict, common.checkAc
}); });
// new menu item // new menu item
router.post('/admin/settings/menu/new', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/settings/menu/new', restrict, checkAccess, (req, res) => {
let result = common.newMenu(req, res); let result = common.newMenu(req, res);
if(result === false){ if(result === false){
req.session.message = 'Failed creating menu.'; req.session.message = 'Failed creating menu.';
@ -383,7 +384,7 @@ router.post('/admin/settings/menu/new', common.restrict, common.checkAccess, (re
}); });
// update existing menu item // update existing menu item
router.post('/admin/settings/menu/update', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/settings/menu/update', restrict, checkAccess, (req, res) => {
let result = common.updateMenu(req, res); let result = common.updateMenu(req, res);
if(result === false){ if(result === false){
req.session.message = 'Failed updating menu.'; req.session.message = 'Failed updating menu.';
@ -393,7 +394,7 @@ router.post('/admin/settings/menu/update', common.restrict, common.checkAccess,
}); });
// delete menu item // delete menu item
router.get('/admin/settings/menu/delete/:menuid', common.restrict, common.checkAccess, (req, res) => { router.get('/admin/settings/menu/delete/:menuid', restrict, checkAccess, (req, res) => {
let result = common.deleteMenu(req, res, req.params.menuid); let result = common.deleteMenu(req, res, req.params.menuid);
if(result === false){ if(result === false){
req.session.message = 'Failed deleting menu.'; req.session.message = 'Failed deleting menu.';
@ -403,10 +404,10 @@ router.get('/admin/settings/menu/delete/:menuid', common.restrict, common.checkA
}); });
// We call this via a Ajax call to save the order from the sortable list // We call this via a Ajax call to save the order from the sortable list
router.post('/admin/settings/menu/save_order', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/settings/menu/save_order', restrict, checkAccess, (req, res) => {
let result = common.orderMenu(req, res); let result = common.orderMenu(req, res);
if(result === false){ if(result === false){
res.status(400).json({message: 'Failed saving menu order'}); res.status(400).json({ message: 'Failed saving menu order' });
return; return;
} }
res.status(200); res.status(200);
@ -420,9 +421,9 @@ router.post('/admin/api/validate_permalink', (req, res) => {
let query = {}; let query = {};
if(typeof req.body.docId === 'undefined' || req.body.docId === ''){ if(typeof req.body.docId === 'undefined' || req.body.docId === ''){
query = {productPermalink: req.body.permalink}; query = { productPermalink: req.body.permalink };
}else{ }else{
query = {productPermalink: req.body.permalink, _id: {$ne: common.getId(req.body.docId)}}; query = { productPermalink: req.body.permalink, _id: { $ne: common.getId(req.body.docId) } };
} }
db.products.count(query, (err, products) => { db.products.count(query, (err, products) => {
@ -430,16 +431,16 @@ router.post('/admin/api/validate_permalink', (req, res) => {
console.info(err.stack); console.info(err.stack);
} }
if(products > 0){ if(products > 0){
res.status(400).json({message: 'Permalink already exists'}); res.status(400).json({ message: 'Permalink already exists' });
}else{ }else{
res.status(200).json({message: 'Permalink validated successfully'}); res.status(200).json({ message: 'Permalink validated successfully' });
} }
}); });
}); });
// upload the file // upload the file
let upload = multer({dest: 'public/uploads/'}); let upload = multer({ dest: 'public/uploads/' });
router.post('/admin/file/upload', common.restrict, common.checkAccess, upload.single('upload_file'), (req, res, next) => { router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_file'), (req, res, next) => {
const db = req.app.db; const db = req.app.db;
if(req.file){ if(req.file){
@ -461,7 +462,7 @@ router.post('/admin/file/upload', common.restrict, common.checkAccess, upload.si
} }
// get the product form the DB // get the product form the DB
db.products.findOne({_id: common.getId(req.body.productId)}, (err, product) => { db.products.findOne({ _id: common.getId(req.body.productId) }, (err, product) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
// delete the temp file. // delete the temp file.
@ -494,7 +495,7 @@ router.post('/admin/file/upload', common.restrict, common.checkAccess, upload.si
// if there isn't a product featured image, set this one // if there isn't a product featured image, set this one
if(!product.productImage){ if(!product.productImage){
db.products.update({_id: common.getId(req.body.productId)}, {$set: {productImage: imagePath}}, {multi: false}, (err, numReplaced) => { db.products.update({ _id: common.getId(req.body.productId) }, { $set: { productImage: imagePath } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -517,33 +518,33 @@ router.post('/admin/file/upload', common.restrict, common.checkAccess, upload.si
}); });
// delete a file via ajax request // delete a file via ajax request
router.post('/admin/testEmail', common.restrict, (req, res) => { router.post('/admin/testEmail', restrict, (req, res) => {
let config = req.app.config; let config = req.app.config;
// TODO: Should fix this to properly handle result // TODO: Should fix this to properly handle result
common.sendEmail(config.emailAddress, 'expressCart test email', 'Your email settings are working'); common.sendEmail(config.emailAddress, 'expressCart test email', 'Your email settings are working');
res.status(200).json({message: 'Test email sent'}); res.status(200).json({ message: 'Test email sent' });
}); });
// delete a file via ajax request // delete a file via ajax request
router.post('/admin/file/delete', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/file/delete', restrict, checkAccess, (req, res) => {
req.session.message = null; req.session.message = null;
req.session.messageType = null; req.session.messageType = null;
fs.unlink('public/' + req.body.img, (err) => { fs.unlink('public/' + req.body.img, (err) => {
if(err){ if(err){
console.error(colors.red('File delete error: ' + err)); console.error(colors.red('File delete error: ' + err));
res.writeHead(400, {'Content-Type': 'application/text'}); res.writeHead(400, { 'Content-Type': 'application/text' });
res.end('Failed to delete file: ' + err); res.end('Failed to delete file: ' + err);
}else{ }else{
res.writeHead(200, {'Content-Type': 'application/text'}); res.writeHead(200, { 'Content-Type': 'application/text' });
res.end('File deleted successfully'); res.end('File deleted successfully');
} }
}); });
}); });
router.get('/admin/files', common.restrict, (req, res) => { router.get('/admin/files', restrict, (req, res) => {
// loop files in /public/uploads/ // loop files in /public/uploads/
glob('public/uploads/**', {nosort: true}, (er, files) => { glob('public/uploads/**', { nosort: true }, (er, files) => {
// sort array // sort array
files.sort(); files.sort();

View File

@ -4,6 +4,7 @@ const colors = require('colors');
const randtoken = require('rand-token'); const randtoken = require('rand-token');
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
const common = require('../lib/common'); const common = require('../lib/common');
const { restrict } = require('../lib/auth');
// insert a customer // insert a customer
router.post('/customer/create', (req, res) => { router.post('/customer/create', (req, res) => {
@ -24,7 +25,7 @@ router.post('/customer/create', (req, res) => {
}; };
// check for existing customer // check for existing customer
db.customers.findOne({email: req.body.email}, (err, customer) => { db.customers.findOne({ email: req.body.email }, (err, customer) => {
if(customer){ if(customer){
res.status(400).json({ res.status(400).json({
err: 'A customer already exists with that email address' err: 'A customer already exists with that email address'
@ -59,10 +60,10 @@ router.post('/customer/create', (req, res) => {
}); });
// render the customer view // render the customer view
router.get('/admin/customer/view/:id?', common.restrict, (req, res) => { router.get('/admin/customer/view/:id?', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.customers.findOne({_id: common.getId(req.params.id)}, (err, result) => { db.customers.findOne({ _id: common.getId(req.params.id) }, (err, result) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -82,10 +83,10 @@ router.get('/admin/customer/view/:id?', common.restrict, (req, res) => {
}); });
// customers list // customers list
router.get('/admin/customers', common.restrict, (req, res) => { router.get('/admin/customers', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.customers.find({}).limit(20).sort({created: -1}).toArray((err, customers) => { db.customers.find({}).limit(20).sort({ created: -1 }).toArray((err, customers) => {
res.render('customers', { res.render('customers', {
title: 'Customers - List', title: 'Customers - List',
admin: true, admin: true,
@ -100,7 +101,7 @@ router.get('/admin/customers', common.restrict, (req, res) => {
}); });
// Filtered customers list // Filtered customers list
router.get('/admin/customers/filter/:search', common.restrict, (req, res, next) => { router.get('/admin/customers/filter/:search', restrict, (req, res, next) => {
const db = req.app.db; const db = req.app.db;
let searchTerm = req.params.search; let searchTerm = req.params.search;
let customersIndex = req.app.customersIndex; let customersIndex = req.app.customersIndex;
@ -111,7 +112,7 @@ router.get('/admin/customers/filter/:search', common.restrict, (req, res, next)
}); });
// we search on the lunr indexes // we search on the lunr indexes
db.customers.find({_id: {$in: lunrIdArray}}).sort({created: -1}).toArray((err, customers) => { db.customers.find({ _id: { $in: lunrIdArray } }).sort({ created: -1 }).toArray((err, customers) => {
if(err){ if(err){
console.error(colors.red('Error searching', err)); console.error(colors.red('Error searching', err));
} }
@ -193,11 +194,11 @@ router.post('/customer/forgotten_action', (req, res) => {
let passwordToken = randtoken.generate(30); let passwordToken = randtoken.generate(30);
// find the user // find the user
db.customers.findOne({email: req.body.email}, (err, customer) => { db.customers.findOne({ email: req.body.email }, (err, customer) => {
// if we have a customer, set a token, expiry and email it // if we have a customer, set a token, expiry and email it
if(customer){ if(customer){
let tokenExpiry = Date.now() + 3600000; let tokenExpiry = Date.now() + 3600000;
db.customers.update({email: req.body.email}, {$set: {resetToken: passwordToken, resetTokenExpiry: tokenExpiry}}, {multi: false}, (err, numReplaced) => { db.customers.update({ email: req.body.email }, { $set: { resetToken: passwordToken, resetTokenExpiry: tokenExpiry } }, { multi: false }, (err, numReplaced) => {
// send forgotten password email // send forgotten password email
let mailOpts = { let mailOpts = {
to: req.body.email, to: req.body.email,
@ -227,7 +228,7 @@ router.get('/customer/reset/:token', (req, res) => {
const db = req.app.db; const db = req.app.db;
// Find the customer using the token // Find the customer using the token
db.customers.findOne({resetToken: req.params.token, resetTokenExpiry: {$gt: Date.now()}}, (err, customer) => { db.customers.findOne({ resetToken: req.params.token, resetTokenExpiry: { $gt: Date.now() } }, (err, customer) => {
if(!customer){ if(!customer){
req.session.message = 'Password reset token is invalid or has expired'; req.session.message = 'Password reset token is invalid or has expired';
req.session.message_type = 'danger'; req.session.message_type = 'danger';
@ -254,7 +255,7 @@ router.post('/customer/reset/:token', (req, res) => {
const db = req.app.db; const db = req.app.db;
// get the customer // get the customer
db.customers.findOne({resetToken: req.params.token, resetTokenExpiry: {$gt: Date.now()}}, (err, customer) => { db.customers.findOne({ resetToken: req.params.token, resetTokenExpiry: { $gt: Date.now() } }, (err, customer) => {
if(!customer){ if(!customer){
req.session.message = 'Password reset token is invalid or has expired'; req.session.message = 'Password reset token is invalid or has expired';
req.session.message_type = 'danger'; req.session.message_type = 'danger';
@ -263,7 +264,7 @@ router.post('/customer/reset/:token', (req, res) => {
// update the password and remove the token // update the password and remove the token
let newPassword = bcrypt.hashSync(req.body.password, 10); let newPassword = bcrypt.hashSync(req.body.password, 10);
db.customers.update({email: customer.email}, {$set: {password: newPassword, resetToken: undefined, resetTokenExpiry: undefined}}, {multi: false}, (err, numReplaced) => { db.customers.update({ email: customer.email }, { $set: { password: newPassword, resetToken: undefined, resetTokenExpiry: undefined } }, { multi: false }, (err, numReplaced) => {
let mailOpts = { let mailOpts = {
to: customer.email, to: customer.email,
subject: 'Password successfully reset', subject: 'Password successfully reset',

View File

@ -11,7 +11,7 @@ router.get('/payment/:orderId', async (req, res, next) => {
let config = req.app.config; let config = req.app.config;
// render the payment complete message // render the payment complete message
db.orders.findOne({_id: common.getId(req.params.orderId)}, async (err, order) => { db.orders.findOne({ _id: common.getId(req.params.orderId) }, async (err, order) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -19,7 +19,7 @@ router.get('/payment/:orderId', async (req, res, next) => {
// If stock management is turned on payment approved update stock level // If stock management is turned on payment approved update stock level
if(config.trackStock && req.session.paymentApproved){ if(config.trackStock && req.session.paymentApproved){
order.orderProducts.forEach(async (product) => { order.orderProducts.forEach(async (product) => {
const dbProduct = await db.products.findOne({_id: common.getId(product.productId)}); const dbProduct = await db.products.findOne({ _id: common.getId(product.productId) });
let newStockLevel = dbProduct.productStock - product.quantity; let newStockLevel = dbProduct.productStock - product.quantity;
if(newStockLevel < 1){ if(newStockLevel < 1){
newStockLevel = 0; newStockLevel = 0;
@ -32,7 +32,7 @@ router.get('/payment/:orderId', async (req, res, next) => {
$set: { $set: {
productStock: newStockLevel productStock: newStockLevel
} }
}, {multi: false}); }, { multi: false });
}); });
} }
@ -122,13 +122,13 @@ router.get('/product/:id', (req, res) => {
let db = req.app.db; let db = req.app.db;
let config = req.app.config; let config = req.app.config;
db.products.findOne({$or: [{_id: common.getId(req.params.id)}, {productPermalink: req.params.id}]}, (err, result) => { db.products.findOne({ $or: [{ _id: common.getId(req.params.id) }, { productPermalink: req.params.id }] }, (err, result) => {
// render 404 if page is not published // render 404 if page is not published
if(err){ if(err){
res.render('error', {title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config}); res.render('error', { title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config });
} }
if(err || result == null || result.productPublished === 'false'){ if(err || result == null || result.productPublished === 'false'){
res.render('error', {title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config}); res.render('error', { title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config });
}else{ }else{
let productOptions = {}; let productOptions = {};
if(result.productOptions){ if(result.productOptions){
@ -180,7 +180,7 @@ router.post('/product/updatecart', (req, res, next) => {
req.session.cart.splice(cartItem.cartIndex, 1); req.session.cart.splice(cartItem.cartIndex, 1);
callback(null); callback(null);
}else{ }else{
db.products.findOne({_id: common.getId(cartItem.productId)}, (err, product) => { db.products.findOne({ _id: common.getId(cartItem.productId) }, (err, product) => {
if(err){ if(err){
console.error(colors.red('Error updating cart', err)); console.error(colors.red('Error updating cart', err));
} }
@ -212,18 +212,18 @@ router.post('/product/updatecart', (req, res, next) => {
common.updateTotalCartAmount(req, res); common.updateTotalCartAmount(req, res);
// Update cart to the DB // Update cart to the DB
await db.cart.update({sessionId: req.session.id}, { await db.cart.update({ sessionId: req.session.id }, {
$set: {cart: req.session.cart} $set: { cart: req.session.cart }
}); });
// show response // show response
if(hasError === false){ if(hasError === false){
res.status(200).json({message: 'Cart successfully updated', totalCartItems: Object.keys(req.session.cart).length}); res.status(200).json({ message: 'Cart successfully updated', totalCartItems: Object.keys(req.session.cart).length });
}else{ }else{
if(stockError){ if(stockError){
res.status(400).json({message: 'There is insufficient stock of this product.', totalCartItems: Object.keys(req.session.cart).length}); res.status(400).json({ message: 'There is insufficient stock of this product.', totalCartItems: Object.keys(req.session.cart).length });
}else{ }else{
res.status(400).json({message: 'There was an error updating the cart', totalCartItems: Object.keys(req.session.cart).length}); res.status(400).json({ message: 'There was an error updating the cart', totalCartItems: Object.keys(req.session.cart).length });
} }
} }
}); });
@ -245,16 +245,16 @@ router.post('/product/removefromcart', (req, res, next) => {
callback(); callback();
}, async () => { }, async () => {
// Update cart in DB // Update cart in DB
await db.cart.update({sessionId: req.session.id}, { await db.cart.update({ sessionId: req.session.id }, {
$set: {cart: req.session.cart} $set: { cart: req.session.cart }
}); });
// update total cart amount // update total cart amount
common.updateTotalCartAmount(req, res); common.updateTotalCartAmount(req, res);
if(itemRemoved === false){ if(itemRemoved === false){
return res.status(400).json({message: 'Product not found in cart'}); return res.status(400).json({ message: 'Product not found in cart' });
} }
return res.status(200).json({message: 'Product successfully removed', totalCartItems: Object.keys(req.session.cart).length}); return res.status(200).json({ message: 'Product successfully removed', totalCartItems: Object.keys(req.session.cart).length });
}); });
}); });
@ -267,11 +267,11 @@ router.post('/product/emptycart', async (req, res, next) => {
delete req.session.orderId; delete req.session.orderId;
// Remove cart from DB // Remove cart from DB
await db.cart.removeOne({sessionId: req.session.id}); await db.cart.removeOne({ sessionId: req.session.id });
// update total cart amount // update total cart amount
common.updateTotalCartAmount(req, res); common.updateTotalCartAmount(req, res);
res.status(200).json({message: 'Cart successfully emptied', totalCartItems: 0}); res.status(200).json({ message: 'Cart successfully emptied', totalCartItems: 0 });
}); });
// Add item to cart // Add item to cart
@ -292,15 +292,15 @@ router.post('/product/addtocart', (req, res, next) => {
} }
// Get the item from the DB // Get the item from the DB
db.products.findOne({_id: common.getId(req.body.productId)}, async (err, product) => { db.products.findOne({ _id: common.getId(req.body.productId) }, async (err, product) => {
if(err){ if(err){
console.error(colors.red('Error adding to cart', err)); console.error(colors.red('Error adding to cart', err));
return res.status(400).json({message: 'Error updating cart. Please try again.'}); return res.status(400).json({ message: 'Error updating cart. Please try again.' });
} }
// No product found // No product found
if(!product){ if(!product){
return res.status(400).json({message: 'Error updating cart. Please try again.'}); return res.status(400).json({ message: 'Error updating cart. Please try again.' });
} }
// If stock management on check there is sufficient stock for this product // If stock management on check there is sufficient stock for this product
@ -308,14 +308,14 @@ router.post('/product/addtocart', (req, res, next) => {
const stockHeld = await db.cart.aggregate( const stockHeld = await db.cart.aggregate(
{ {
$match: { $match: {
cart: {$elemMatch: {productId: product._id.toString()}} cart: { $elemMatch: { productId: product._id.toString() } }
} }
}, },
{$unwind: '$cart'}, { $unwind: '$cart' },
{ {
$group: { $group: {
_id: '$cart.productId', _id: '$cart.productId',
sumHeld: {$sum: '$cart.quantity'} sumHeld: { $sum: '$cart.quantity' }
} }
}, },
{ {
@ -327,12 +327,12 @@ router.post('/product/addtocart', (req, res, next) => {
// If there is stock // If there is stock
if(stockHeld.length > 0){ if(stockHeld.length > 0){
const totalHeld = _.find(stockHeld, {_id: product._id.toString()}).sumHeld; const totalHeld = _.find(stockHeld, { _id: product._id.toString() }).sumHeld;
const netStock = product.productStock - totalHeld; const netStock = product.productStock - totalHeld;
// Check there is sufficient stock // Check there is sufficient stock
if(productQuantity > netStock){ if(productQuantity > netStock){
return res.status(400).json({message: 'There is insufficient stock of this product.'}); return res.status(400).json({ message: 'There is insufficient stock of this product.' });
} }
} }
} }
@ -383,16 +383,16 @@ router.post('/product/addtocart', (req, res, next) => {
} }
// Update cart to the DB // Update cart to the DB
await db.cart.update({sessionId: req.session.id}, { await db.cart.update({ sessionId: req.session.id }, {
$set: {cart: req.session.cart} $set: { cart: req.session.cart }
}, {upsert: true}); }, { upsert: true });
// update total cart amount // update total cart amount
common.updateTotalCartAmount(req, res); common.updateTotalCartAmount(req, res);
// update how many products in the shopping cart // update how many products in the shopping cart
req.session.cartTotalItems = req.session.cart.reduce((a, b) => +a + +b.quantity, 0); req.session.cartTotalItems = req.session.cart.reduce((a, b) => +a + +b.quantity, 0);
return res.status(200).json({message: 'Cart successfully updated', totalCartItems: req.session.cartTotalItems}); return res.status(200).json({ message: 'Cart successfully updated', totalCartItems: req.session.cartTotalItems });
}); });
}); });
@ -415,7 +415,7 @@ router.get('/search/:searchTerm/:pageNum?', (req, res) => {
} }
Promise.all([ Promise.all([
common.getData(req, pageNum, {_id: {$in: lunrIdArray}}), common.getData(req, pageNum, { _id: { $in: lunrIdArray } }),
common.getMenu(db) common.getMenu(db)
]) ])
.then(([results, menu]) => { .then(([results, menu]) => {
@ -469,7 +469,7 @@ router.get('/category/:cat/:pageNum?', (req, res) => {
} }
Promise.all([ Promise.all([
common.getData(req, pageNum, {_id: {$in: lunrIdArray}}), common.getData(req, pageNum, { _id: { $in: lunrIdArray } }),
common.getMenu(db) common.getMenu(db)
]) ])
.then(([results, menu]) => { .then(([results, menu]) => {
@ -521,7 +521,7 @@ router.get('/sitemap.xml', (req, res, next) => {
hostname: config.baseUrl, hostname: config.baseUrl,
cacheTime: 600000, cacheTime: 600000,
urls: [ urls: [
{url: '/', changefreq: 'weekly', priority: 1.0} { url: '/', changefreq: 'weekly', priority: 1.0 }
] ]
}); });
@ -625,7 +625,7 @@ router.get('/:page?', (req, res, next) => {
return; return;
} }
// lets look for a page // lets look for a page
db.pages.findOne({pageSlug: req.params.page, pageEnabled: 'true'}, async (err, page) => { db.pages.findOne({ pageSlug: req.params.page, pageEnabled: 'true' }, async (err, page) => {
if(err){ if(err){
console.error(colors.red('Error getting page', err)); console.error(colors.red('Error getting page', err));
} }

View File

@ -1,13 +1,14 @@
const express = require('express'); const express = require('express');
const common = require('../lib/common'); const common = require('../lib/common');
const { restrict, checkAccess } = require('../lib/auth');
const router = express.Router(); const router = express.Router();
// Show orders // Show orders
router.get('/admin/orders', common.restrict, (req, res, next) => { router.get('/admin/orders', restrict, (req, res, next) => {
const db = req.app.db; const db = req.app.db;
// Top 10 products // Top 10 products
db.orders.find({}).sort({'orderDate': -1}).limit(10).toArray((err, orders) => { db.orders.find({}).sort({ 'orderDate': -1 }).limit(10).toArray((err, orders) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -33,7 +34,7 @@ router.get('/admin/orders', common.restrict, (req, res, next) => {
}); });
// Admin section // Admin section
router.get('/admin/orders/bystatus/:orderstatus', common.restrict, (req, res, next) => { router.get('/admin/orders/bystatus/:orderstatus', restrict, (req, res, next) => {
const db = req.app.db; const db = req.app.db;
if(typeof req.params.orderstatus === 'undefined'){ if(typeof req.params.orderstatus === 'undefined'){
@ -43,7 +44,7 @@ router.get('/admin/orders/bystatus/:orderstatus', common.restrict, (req, res, ne
// case insensitive search // case insensitive search
let regex = new RegExp(['^', req.params.orderstatus, '$'].join(''), 'i'); let regex = new RegExp(['^', req.params.orderstatus, '$'].join(''), 'i');
db.orders.find({orderStatus: regex}).sort({'orderDate': -1}).limit(10).toArray((err, orders) => { db.orders.find({ orderStatus: regex }).sort({ 'orderDate': -1 }).limit(10).toArray((err, orders) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -71,9 +72,9 @@ router.get('/admin/orders/bystatus/:orderstatus', common.restrict, (req, res, ne
}); });
// render the editor // render the editor
router.get('/admin/order/view/:id', common.restrict, (req, res) => { router.get('/admin/order/view/:id', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.orders.findOne({_id: common.getId(req.params.id)}, (err, result) => { db.orders.findOne({ _id: common.getId(req.params.id) }, (err, result) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -92,7 +93,7 @@ router.get('/admin/order/view/:id', common.restrict, (req, res) => {
}); });
// Admin section // Admin section
router.get('/admin/orders/filter/:search', common.restrict, (req, res, next) => { router.get('/admin/orders/filter/:search', restrict, (req, res, next) => {
const db = req.app.db; const db = req.app.db;
let searchTerm = req.params.search; let searchTerm = req.params.search;
let ordersIndex = req.app.ordersIndex; let ordersIndex = req.app.ordersIndex;
@ -103,7 +104,7 @@ router.get('/admin/orders/filter/:search', common.restrict, (req, res, next) =>
}); });
// we search on the lunr indexes // we search on the lunr indexes
db.orders.find({_id: {$in: lunrIdArray}}).toArray((err, orders) => { db.orders.find({ _id: { $in: lunrIdArray } }).toArray((err, orders) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -130,11 +131,11 @@ router.get('/admin/orders/filter/:search', common.restrict, (req, res, next) =>
}); });
// order product // order product
router.get('/admin/order/delete/:id', common.restrict, (req, res) => { router.get('/admin/order/delete/:id', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
// remove the article // remove the article
db.orders.remove({_id: common.getId(req.params.id)}, {}, (err, numRemoved) => { db.orders.remove({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -150,13 +151,13 @@ router.get('/admin/order/delete/:id', common.restrict, (req, res) => {
}); });
// update order status // update order status
router.post('/admin/order/statusupdate', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/order/statusupdate', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.orders.update({_id: common.getId(req.body.order_id)}, {$set: {orderStatus: req.body.status}}, {multi: false}, (err, numReplaced) => { db.orders.update({ _id: common.getId(req.body.order_id) }, { $set: { orderStatus: req.body.status } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
res.status(200).json({message: 'Status successfully updated'}); res.status(200).json({ message: 'Status successfully updated' });
}); });
}); });

View File

@ -14,7 +14,7 @@ router.get('/checkout_return', (req, res, next) => {
let paymentId = req.session.paymentId; let paymentId = req.session.paymentId;
let payerId = req.query['PayerID']; let payerId = req.query['PayerID'];
let details = {'payer_id': payerId}; let details = { 'payer_id': payerId };
paypal.payment.execute(paymentId, details, (error, payment) => { paypal.payment.execute(paymentId, details, (error, payment) => {
let paymentApproved = false; let paymentApproved = false;
let paymentMessage = ''; let paymentMessage = '';
@ -66,11 +66,11 @@ router.get('/checkout_return', (req, res, next) => {
} }
// update the order status // update the order status
db.orders.update({_id: common.getId(paymentOrderId)}, {$set: {orderStatus: paymentStatus}}, {multi: false}, (err, numReplaced) => { db.orders.update({ _id: common.getId(paymentOrderId) }, { $set: { orderStatus: paymentStatus } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
db.orders.findOne({_id: common.getId(paymentOrderId)}, (err, order) => { db.orders.findOne({ _id: common.getId(paymentOrderId) }, (err, order) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }

View File

@ -1,15 +1,16 @@
const express = require('express'); const express = require('express');
const common = require('../lib/common'); const common = require('../lib/common');
const { restrict, checkAccess } = require('../lib/auth');
const colors = require('colors'); const colors = require('colors');
const rimraf = require('rimraf'); const rimraf = require('rimraf');
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const router = express.Router(); const router = express.Router();
router.get('/admin/products', common.restrict, (req, res, next) => { router.get('/admin/products', restrict, (req, res, next) => {
const db = req.app.db; const db = req.app.db;
// get the top results // get the top results
db.products.find({}).sort({'productAddedDate': -1}).limit(10).toArray((err, topResults) => { db.products.find({}).sort({ 'productAddedDate': -1 }).limit(10).toArray((err, topResults) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -37,7 +38,7 @@ router.get('/admin/products/filter/:search', (req, res, next) => {
}); });
// we search on the lunr indexes // we search on the lunr indexes
db.products.find({_id: {$in: lunrIdArray}}).toArray((err, results) => { db.products.find({ _id: { $in: lunrIdArray } }).toArray((err, results) => {
if(err){ if(err){
console.error(colors.red('Error searching', err)); console.error(colors.red('Error searching', err));
} }
@ -56,7 +57,7 @@ router.get('/admin/products/filter/:search', (req, res, next) => {
}); });
// insert form // insert form
router.get('/admin/product/new', common.restrict, common.checkAccess, (req, res) => { router.get('/admin/product/new', restrict, checkAccess, (req, res) => {
res.render('product_new', { res.render('product_new', {
title: 'New product', title: 'New product',
session: req.session, session: req.session,
@ -74,7 +75,7 @@ router.get('/admin/product/new', common.restrict, common.checkAccess, (req, res)
}); });
// insert new product form action // insert new product form action
router.post('/admin/product/insert', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
let doc = { let doc = {
@ -90,7 +91,7 @@ router.post('/admin/product/insert', common.restrict, common.checkAccess, (req,
productStock: req.body.frmProductStock ? parseInt(req.body.frmProductStock) : null productStock: req.body.frmProductStock ? parseInt(req.body.frmProductStock) : null
}; };
db.products.count({'productPermalink': req.body.frmProductPermalink}, (err, product) => { db.products.count({ 'productPermalink': req.body.frmProductPermalink }, (err, product) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -151,11 +152,11 @@ router.post('/admin/product/insert', common.restrict, common.checkAccess, (req,
}); });
// render the editor // render the editor
router.get('/admin/product/edit/:id', common.restrict, common.checkAccess, (req, res) => { router.get('/admin/product/edit/:id', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
common.getImages(req.params.id, req, res, (images) => { common.getImages(req.params.id, req, res, (images) => {
db.products.findOne({_id: common.getId(req.params.id)}, (err, result) => { db.products.findOne({ _id: common.getId(req.params.id) }, (err, result) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -182,10 +183,10 @@ router.get('/admin/product/edit/:id', common.restrict, common.checkAccess, (req,
}); });
// Update an existing product form action // Update an existing product form action
router.post('/admin/product/update', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.products.findOne({_id: common.getId(req.body.frmProductId)}, (err, product) => { db.products.findOne({ _id: common.getId(req.body.frmProductId) }, (err, product) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
req.session.message = 'Failed updating product.'; req.session.message = 'Failed updating product.';
@ -193,7 +194,7 @@ router.post('/admin/product/update', common.restrict, common.checkAccess, (req,
res.redirect('/admin/product/edit/' + req.body.frmProductId); res.redirect('/admin/product/edit/' + req.body.frmProductId);
return; return;
} }
db.products.count({'productPermalink': req.body.frmProductPermalink, _id: {$ne: common.getId(product._id)}}, (err, count) => { db.products.count({ 'productPermalink': req.body.frmProductPermalink, _id: { $ne: common.getId(product._id) } }, (err, count) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
req.session.message = 'Failed updating product.'; req.session.message = 'Failed updating product.';
@ -244,7 +245,7 @@ router.post('/admin/product/update', common.restrict, common.checkAccess, (req,
productDoc['productImage'] = product.productImage; productDoc['productImage'] = product.productImage;
} }
db.products.update({_id: common.getId(req.body.frmProductId)}, {$set: productDoc}, {}, (err, numReplaced) => { db.products.update({ _id: common.getId(req.body.frmProductId) }, { $set: productDoc }, {}, (err, numReplaced) => {
if(err){ if(err){
console.error(colors.red('Failed to save product: ' + err)); console.error(colors.red('Failed to save product: ' + err));
req.session.message = 'Failed to save. Please try again'; req.session.message = 'Failed to save. Please try again';
@ -267,11 +268,11 @@ router.post('/admin/product/update', common.restrict, common.checkAccess, (req,
}); });
// delete product // delete product
router.get('/admin/product/delete/:id', common.restrict, common.checkAccess, (req, res) => { router.get('/admin/product/delete/:id', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
// remove the article // remove the article
db.products.remove({_id: common.getId(req.params.id)}, {}, (err, numRemoved) => { db.products.remove({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -294,10 +295,10 @@ router.get('/admin/product/delete/:id', common.restrict, common.checkAccess, (re
}); });
// update the published state based on an ajax call from the frontend // update the published state based on an ajax call from the frontend
router.post('/admin/product/published_state', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/product/published_state', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.products.update({_id: common.getId(req.body.id)}, {$set: {productPublished: req.body.state}}, {multi: false}, (err, numReplaced) => { db.products.update({ _id: common.getId(req.body.id) }, { $set: { productPublished: req.body.state } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.error(colors.red('Failed to update the published state: ' + err)); console.error(colors.red('Failed to update the published state: ' + err));
res.status(400).json('Published state not updated'); res.status(400).json('Published state not updated');
@ -308,40 +309,40 @@ router.post('/admin/product/published_state', common.restrict, common.checkAcces
}); });
// set as main product image // set as main product image
router.post('/admin/product/setasmainimage', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/product/setasmainimage', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
// update the productImage to the db // update the productImage to the db
db.products.update({_id: common.getId(req.body.product_id)}, {$set: {productImage: req.body.productImage}}, {multi: false}, (err, numReplaced) => { db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: req.body.productImage } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
res.status(400).json({message: 'Unable to set as main image. Please try again.'}); res.status(400).json({ message: 'Unable to set as main image. Please try again.' });
}else{ }else{
res.status(200).json({message: 'Main image successfully set'}); res.status(200).json({ message: 'Main image successfully set' });
} }
}); });
}); });
// deletes a product image // deletes a product image
router.post('/admin/product/deleteimage', common.restrict, common.checkAccess, (req, res) => { router.post('/admin/product/deleteimage', restrict, checkAccess, (req, res) => {
const db = req.app.db; const db = req.app.db;
// get the productImage from the db // get the productImage from the db
db.products.findOne({_id: common.getId(req.body.product_id)}, (err, product) => { db.products.findOne({ _id: common.getId(req.body.product_id) }, (err, product) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
if(req.body.productImage === product.productImage){ if(req.body.productImage === product.productImage){
// set the produt_image to null // set the produt_image to null
db.products.update({_id: common.getId(req.body.product_id)}, {$set: {productImage: null}}, {multi: false}, (err, numReplaced) => { db.products.update({ _id: common.getId(req.body.product_id) }, { $set: { productImage: null } }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
// remove the image from disk // remove the image from disk
fs.unlink(path.join('public', req.body.productImage), (err) => { fs.unlink(path.join('public', req.body.productImage), (err) => {
if(err){ if(err){
res.status(400).json({message: 'Image not removed, please try again.'}); res.status(400).json({ message: 'Image not removed, please try again.' });
}else{ }else{
res.status(200).json({message: 'Image successfully deleted'}); res.status(200).json({ message: 'Image successfully deleted' });
} }
}); });
}); });
@ -349,9 +350,9 @@ router.post('/admin/product/deleteimage', common.restrict, common.checkAccess, (
// remove the image from disk // remove the image from disk
fs.unlink(path.join('public', req.body.productImage), (err) => { fs.unlink(path.join('public', req.body.productImage), (err) => {
if(err){ if(err){
res.status(400).json({message: 'Image not removed, please try again.'}); res.status(400).json({ message: 'Image not removed, please try again.' });
}else{ }else{
res.status(200).json({message: 'Image successfully deleted'}); res.status(200).json({ message: 'Image successfully deleted' });
} }
}); });
} }

View File

@ -1,11 +1,12 @@
const express = require('express'); const express = require('express');
const common = require('../lib/common'); const common = require('../lib/common');
const { restrict } = require('../lib/auth');
const colors = require('colors'); const colors = require('colors');
const bcrypt = require('bcryptjs'); const bcrypt = require('bcryptjs');
const url = require('url'); const url = require('url');
const router = express.Router(); const router = express.Router();
router.get('/admin/users', common.restrict, (req, res) => { router.get('/admin/users', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.users.find({}).toArray((err, users) => { db.users.find({}).toArray((err, users) => {
if(err){ if(err){
@ -26,9 +27,9 @@ router.get('/admin/users', common.restrict, (req, res) => {
}); });
// edit user // edit user
router.get('/admin/user/edit/:id', common.restrict, (req, res) => { router.get('/admin/user/edit/:id', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
db.users.findOne({_id: common.getId(req.params.id)}, (err, user) => { db.users.findOne({ _id: common.getId(req.params.id) }, (err, user) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -55,7 +56,7 @@ router.get('/admin/user/edit/:id', common.restrict, (req, res) => {
}); });
// users new // users new
router.get('/admin/user/new', common.restrict, (req, res) => { router.get('/admin/user/new', restrict, (req, res) => {
res.render('user_new', { res.render('user_new', {
title: 'User - New', title: 'User - New',
admin: true, admin: true,
@ -68,10 +69,10 @@ router.get('/admin/user/new', common.restrict, (req, res) => {
}); });
// delete user // delete user
router.get('/admin/user/delete/:id', common.restrict, (req, res) => { router.get('/admin/user/delete/:id', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
if(req.session.isAdmin === true){ if(req.session.isAdmin === true){
db.users.remove({_id: common.getId(req.params.id)}, {}, (err, numRemoved) => { db.users.remove({ _id: common.getId(req.params.id) }, {}, (err, numRemoved) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -87,13 +88,13 @@ router.get('/admin/user/delete/:id', common.restrict, (req, res) => {
}); });
// update a user // update a user
router.post('/admin/user/update', common.restrict, (req, res) => { router.post('/admin/user/update', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
let isAdmin = req.body.user_admin === 'on'; let isAdmin = req.body.user_admin === 'on';
// get the user we want to update // get the user we want to update
db.users.findOne({_id: common.getId(req.body.userId)}, (err, user) => { db.users.findOne({ _id: common.getId(req.body.userId) }, (err, user) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -120,10 +121,10 @@ router.post('/admin/user/update', common.restrict, (req, res) => {
updateDoc.userPassword = bcrypt.hashSync(req.body.userPassword); updateDoc.userPassword = bcrypt.hashSync(req.body.userPassword);
} }
db.users.update({_id: common.getId(req.body.userId)}, db.users.update({ _id: common.getId(req.body.userId) },
{ {
$set: updateDoc $set: updateDoc
}, {multi: false}, (err, numReplaced) => { }, { multi: false }, (err, numReplaced) => {
if(err){ if(err){
console.error(colors.red('Failed updating user: ' + err)); console.error(colors.red('Failed updating user: ' + err));
req.session.message = 'Failed to update user'; req.session.message = 'Failed to update user';
@ -140,7 +141,7 @@ router.post('/admin/user/update', common.restrict, (req, res) => {
}); });
// insert a user // insert a user
router.post('/admin/user/insert', common.restrict, (req, res) => { router.post('/admin/user/insert', restrict, (req, res) => {
const db = req.app.db; const db = req.app.db;
// set the account to admin if using the setup form. Eg: First user account // set the account to admin if using the setup form. Eg: First user account
@ -163,7 +164,7 @@ router.post('/admin/user/insert', common.restrict, (req, res) => {
}; };
// check for existing user // check for existing user
db.users.findOne({'userEmail': req.body.userEmail}, (err, user) => { db.users.findOne({ 'userEmail': req.body.userEmail }, (err, user) => {
if(user){ if(user){
// user already exists with that email address // user already exists with that email address
console.error(colors.red('Failed to insert user, possibly already exists: ' + err)); console.error(colors.red('Failed to insert user, possibly already exists: ' + err));

View File

@ -2,7 +2,7 @@ const test = require('ava');
const fs = require('fs'); const fs = require('fs');
const _ = require('lodash'); const _ = require('lodash');
const app = require('../app'); const app = require('../app');
const common = require('../lib/common'); const { runIndexing, fixProductDates } = require('../lib/indexing');
const session = require('supertest-session'); const session = require('supertest-session');
// Get test data to compare in tests // Get test data to compare in tests
@ -15,7 +15,6 @@ let config;
let products; let products;
let customers; let customers;
let users; let users;
let orders;
let request = null; let request = null;
function setup(db){ function setup(db){
@ -30,7 +29,7 @@ function setup(db){
return Promise.all([ return Promise.all([
db.users.insertMany(jsonData.users), db.users.insertMany(jsonData.users),
db.customers.insertMany(jsonData.customers), db.customers.insertMany(jsonData.customers),
db.products.insertMany(common.fixProductDates(jsonData.products)) db.products.insertMany(fixProductDates(jsonData.products))
]); ]);
}); });
} }
@ -46,7 +45,7 @@ test.before(async () => {
db = app.db; db = app.db;
await setup(db); await setup(db);
await common.runIndexing(app); await runIndexing(app);
// Get some data from DB to use in compares // Get some data from DB to use in compares
products = await db.products.find({}).toArray(); products = await db.products.find({}).toArray();
@ -70,8 +69,6 @@ test.before(async () => {
await db.orders.insert(order); await db.orders.insert(order);
}); });
// Get orders
orders = await db.orders.find({}).toArray();
resolve(); resolve();
}); });
}); });