From 291a044d0b07f172f99c72696dc2dac20872f6f3 Mon Sep 17 00:00:00 2001 From: Mark Moffat Date: Sat, 15 Jun 2019 14:16:08 +0930 Subject: [PATCH] Linting and refactoring --- .eslintrc.json | 11 +- app.js | 11 +- lib/auth.js | 92 ++++++++ lib/common.js | 340 +++++++----------------------- lib/indexing.js | 142 +++++++++++++ lib/testdata.js | 9 +- public/javascripts/expressCart.js | 20 +- routes/admin.js | 107 +++++----- routes/customer.js | 25 +-- routes/index.js | 68 +++--- routes/order.js | 27 +-- routes/payments/paypal.js | 6 +- routes/product.js | 55 ++--- routes/user.js | 25 +-- test/test.js | 9 +- 15 files changed, 501 insertions(+), 446 deletions(-) create mode 100644 lib/auth.js create mode 100644 lib/indexing.js diff --git a/.eslintrc.json b/.eslintrc.json index 560e01b..e9f9b36 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -17,7 +17,7 @@ }, "rules": { "quotes": ["error", "single"], - "prefer-arrow-callback": 2, + "prefer-arrow-callback": [ "error", { "allowNamedFunctions": true } ], "consistent-return": 2, "no-var" : 2, "new-cap" : 0, @@ -27,11 +27,16 @@ "space-unary-ops" : 2, "no-undef": 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-blocks": ["error", "never"], "camelcase": 0, "handle-callback-err": ["error", "none"], - "object-curly-spacing": ["error", "never"] + "object-curly-spacing": ["error", "always"] } } \ No newline at end of file diff --git a/app.js b/app.js index 5002b2d..463a482 100644 --- a/app.js +++ b/app.js @@ -12,12 +12,13 @@ const helmet = require('helmet'); const colors = require('colors'); const cron = require('node-cron'); 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'); // Validate our settings schema 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')); if(baseConfig === false){ @@ -226,7 +227,7 @@ 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(bodyParser.urlencoded({ extended: false })); app.use(cookieParser('5TOCyfH3HuszKGzFZntk')); app.use(session({ resave: true, @@ -345,7 +346,7 @@ initDb(config.databaseConnectionString, async (err, db) => { // Remove any invalid cart holds 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 if(process.env.NODE_ENV !== 'test'){ try{ - await common.runIndexing(app); + await runIndexing(app); }catch(ex){ console.error(colors.red('Error setting up indexes:' + err)); } diff --git a/lib/auth.js b/lib/auth.js new file mode 100644 index 0000000..95bbbf8 --- /dev/null +++ b/lib/auth.js @@ -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 +}; diff --git a/lib/common.js b/lib/common.js index 8f8fcf4..f6c55ef 100755 --- a/lib/common.js +++ b/lib/common.js @@ -1,7 +1,6 @@ const _ = require('lodash'); const uglifycss = require('uglifycss'); const colors = require('colors'); -const lunr = require('lunr'); const cheerio = require('cheerio'); const fs = require('fs'); const path = require('path'); @@ -11,34 +10,10 @@ const nodemailer = require('nodemailer'); const sanitizeHtml = require('sanitize-html'); const escape = require('html-entities').AllHtmlEntities; const mkdirp = require('mkdirp'); -let 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'} -]; +const ObjectId = require('mongodb').ObjectID; // Allowed mime types for product images -exports.allowedMimeType = [ +const allowedMimeType = [ 'image/jpeg', 'image/png', 'image/gif', @@ -46,54 +21,14 @@ exports.allowedMimeType = [ 'image/webp' ]; -exports.fileSizeLimit = 10485760; +const fileSizeLimit = 10485760; // common functions -exports.restrict = (req, res, next) => { - 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) => { +const cleanHtml = (html) => { return sanitizeHtml(html); }; -exports.mongoSanitize = (param) => { +const mongoSanitize = (param) => { if(param instanceof Object){ for(const key in param){ if(/^\$/.test(key)){ @@ -104,34 +39,14 @@ exports.mongoSanitize = (param) => { return param; }; -exports.checkboxBool = (param) => { +const checkboxBool = (param) => { if(param && param === 'on'){ return true; } return false; }; -// Middleware to check for admin access for certain route -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) => { +const showCartCloseBtn = (page) => { let showCartCloseButton = true; if(page === 'checkout' || page === 'pay'){ showCartCloseButton = false; @@ -141,13 +56,13 @@ exports.showCartCloseBtn = (page) => { }; // adds products to sitemap.xml -exports.addSitemapProducts = (req, res, cb) => { +const addSitemapProducts = (req, res, cb) => { let db = req.app.db; - let config = exports.getConfig(); + let config = getConfig(); let hostname = config.baseUrl; - db.products.find({productPublished: 'true'}).toArray((err, products) => { + db.products.find({ productPublished: 'true' }).toArray((err, products) => { let posts = []; if(err){ cb(null, posts); @@ -169,7 +84,7 @@ exports.addSitemapProducts = (req, res, cb) => { }); }; -exports.clearSessionValue = (session, sessionVar) => { +const clearSessionValue = (session, sessionVar) => { let temp; if(session){ temp = session[sessionVar]; @@ -178,8 +93,8 @@ exports.clearSessionValue = (session, sessionVar) => { return temp; }; -exports.updateTotalCartAmount = (req, res) => { - let config = exports.getConfig(); +const updateTotalCartAmount = (req, res) => { + let config = getConfig(); req.session.totalCartAmount = 0; @@ -196,7 +111,7 @@ exports.updateTotalCartAmount = (req, res) => { } }; -exports.checkDirectorySync = (directory) => { +const checkDirectorySync = (directory) => { try{ fs.statSync(directory); }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()); }; -exports.getImages = (dir, req, res, callback) => { +const getImages = (dir, req, res, callback) => { let db = req.app.db; - db.products.findOne({_id: exports.getId(dir)}, (err, product) => { + db.products.findOne({ _id: getId(dir) }, (err, product) => { if(err){ console.error(colors.red('Error getting images', err)); } // 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 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'); if(fs.existsSync(filename)){ return filename; @@ -257,8 +172,8 @@ exports.getConfigFilename = () => { return path.join(__dirname, '../config', 'settings.json'); }; -exports.getConfig = () => { - let config = JSON.parse(fs.readFileSync(exports.getConfigFilename(), 'utf8')); +const getConfig = () => { + let config = JSON.parse(fs.readFileSync(getConfigFilename(), 'utf8')); config.customCss = typeof config.customCss !== 'undefined' ? escape.decode(config.customCss) : null; config.footerHtml = typeof config.footerHtml !== 'undefined' ? escape.decode(config.footerHtml) : null; config.googleAnalytics = typeof config.googleAnalytics !== 'undefined' ? escape.decode(config.googleAnalytics) : null; @@ -283,8 +198,8 @@ exports.getConfig = () => { return config; }; -exports.getPaymentConfig = () => { - let siteConfig = this.getConfig(); +const getPaymentConfig = () => { + let siteConfig = getConfig(); const gateConfigFile = path.join(__dirname, '../config', `${siteConfig.paymentGateway}.json`); let config = []; @@ -302,8 +217,8 @@ exports.getPaymentConfig = () => { return config; }; -exports.updateConfig = (fields) => { - let settingsFile = exports.getConfig(); +const updateConfig = (fields) => { + let settingsFile = getConfig(); _.forEach(fields, (value, key) => { settingsFile[key] = value; @@ -359,21 +274,21 @@ exports.updateConfig = (fields) => { // write file try{ - fs.writeFileSync(exports.getConfigFilename(), JSON.stringify(settingsFile, null, 4)); + fs.writeFileSync(getConfigFilename(), JSON.stringify(settingsFile, null, 4)); return true; }catch(exception){ return false; } }; -exports.getMenu = (db) => { +const getMenu = (db) => { return db.menu.findOne({}); }; // creates a new menu item -exports.newMenu = (req, res) => { +const newMenu = (req, res) => { const db = req.app.db; - return exports.getMenu(db) + return getMenu(db) .then((menu) => { // if no menu present if(!menu){ @@ -387,7 +302,7 @@ exports.newMenu = (req, res) => { }; 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(() => { return true; }); @@ -399,13 +314,13 @@ exports.newMenu = (req, res) => { }; // delete a menu item -exports.deleteMenu = (req, res, menuIndex) => { +const deleteMenu = (req, res, menuIndex) => { const db = req.app.db; - return exports.getMenu(db) + return getMenu(db) .then((menu) => { // Remove menu item 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(() => { return true; }); @@ -416,15 +331,15 @@ exports.deleteMenu = (req, res, menuIndex) => { }; // updates and existing menu item -exports.updateMenu = (req, res) => { +const updateMenu = (req, res) => { const db = req.app.db; - return exports.getMenu(db) + return getMenu(db) .then((menu) => { // find menu item and update it let menuIndex = _.findIndex(menu.items, ['title', req.body.navId]); menu.items[menuIndex].title = req.body.navMenu; 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(() => { return true; }); @@ -434,7 +349,7 @@ exports.updateMenu = (req, res) => { }); }; -exports.sortMenu = (menu) => { +const sortMenu = (menu) => { if(menu && menu.items){ menu.items = _.sortBy(menu.items, 'order'); return menu; @@ -443,15 +358,15 @@ exports.sortMenu = (menu) => { }; // orders the menu -exports.orderMenu = (req, res) => { +const orderMenu = (req, res) => { const db = req.app.db; - return exports.getMenu(db) + return getMenu(db) .then((menu) => { // update the order for(let i = 0; i < req.body.navId.length; 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(() => { return true; }); @@ -461,8 +376,8 @@ exports.orderMenu = (req, res) => { }); }; -exports.getEmailTemplate = (result) => { - let config = this.getConfig(); +const getEmailTemplate = (result) => { + let config = getConfig(); let template = fs.readFileSync(path.join(__dirname, '../public/email_template.html'), 'utf8'); @@ -480,8 +395,8 @@ exports.getEmailTemplate = (result) => { return $.html(); }; -exports.sendEmail = (to, subject, body) => { - let config = this.getConfig(); +const sendEmail = (to, subject, body) => { + let config = getConfig(); let emailSettings = { host: config.emailHost, @@ -495,7 +410,7 @@ exports.sendEmail = (to, subject, body) => { // outlook needs this setting if(config.emailHost === 'smtp-mail.outlook.com'){ - emailSettings.tls = {ciphers: 'SSLv3'}; + emailSettings.tls = { ciphers: 'SSLv3' }; } let transporter = nodemailer.createTransport(emailSettings); @@ -516,7 +431,7 @@ exports.sendEmail = (to, subject, body) => { }; // gets the correct type of index ID -exports.getId = (id) => { +const getId = (id) => { if(id){ if(id.length !== 24){ return id; @@ -525,9 +440,9 @@ exports.getId = (id) => { return ObjectId(id); }; -exports.getData = (req, page, query) => { +const getData = (req, page, query) => { let db = req.app.db; - let config = exports.getConfig(); + let config = getConfig(); let numberProducts = config.productsPerPage ? config.productsPerPage : 6; let skip = 0; @@ -547,7 +462,7 @@ exports.getData = (req, page, query) => { db.products.count(query) ]) .then((result) => { - const returnData = {data: result[0], totalProducts: result[1]}; + const returnData = { data: result[0], totalProducts: result[1] }; return returnData; }) .catch((err) => { @@ -555,134 +470,31 @@ exports.getData = (req, page, query) => { }); }; -exports.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(); - }); - }); -}; - -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); - }); +module.exports = { + allowedMimeType, + fileSizeLimit, + cleanHtml, + mongoSanitize, + checkboxBool, + showCartCloseBtn, + addSitemapProducts, + clearSessionValue, + updateTotalCartAmount, + checkDirectorySync, + getThemes, + getImages, + getConfigFilename, + getConfig, + getPaymentConfig, + updateConfig, + getMenu, + newMenu, + deleteMenu, + updateMenu, + sortMenu, + orderMenu, + getEmailTemplate, + sendEmail, + getId, + getData }; diff --git a/lib/indexing.js b/lib/indexing.js new file mode 100644 index 0000000..039b24b --- /dev/null +++ b/lib/indexing.js @@ -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 +}; diff --git a/lib/testdata.js b/lib/testdata.js index b586900..d7bac8d 100644 --- a/lib/testdata.js +++ b/lib/testdata.js @@ -1,5 +1,6 @@ -const common = require('./common'); -const{initDb} = require('./db'); +const { getConfig } = require('./common'); +const { initDb } = require('./db'); +const { fixProductDates } = require('./indexing'); const fs = require('fs'); const path = require('path'); @@ -7,7 +8,7 @@ const testData = fs.readFileSync(path.join(__dirname, '..', 'bin', 'testdata.jso const jsonData = JSON.parse(testData); // get config -let config = common.getConfig(); +let config = getConfig(); initDb(config.databaseConnectionString, (err, db) => { Promise.all([ @@ -20,7 +21,7 @@ initDb(config.databaseConnectionString, (err, db) => { Promise.all([ db.users.insertMany(jsonData.users), db.customers.insertMany(jsonData.customers), - db.products.insertMany(common.fixProductDates(jsonData.products)), + db.products.insertMany(fixProductDates(jsonData.products)), db.menu.insertOne(jsonData.menu) ]) .then(() => { diff --git a/public/javascripts/expressCart.js b/public/javascripts/expressCart.js index 39b8262..1aa3105 100644 --- a/public/javascripts/expressCart.js +++ b/public/javascripts/expressCart.js @@ -120,7 +120,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', url: '/admin/product/published_state', - data: {id: this.id, state: this.checked} + data: { id: this.id, state: this.checked } }) .done(function(msg){ showNotification(msg.message, 'success'); @@ -226,7 +226,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', url: '/admin/settings/option/remove/', - data: {productId: $('#frmProductId').val(), optName: name} + data: { productId: $('#frmProductId').val(), optName: name } }) .done(function(msg){ showNotification(msg.message, 'success', true); @@ -467,7 +467,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', 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){ showNotification(msg.message, 'success', true); @@ -524,7 +524,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', url: '/product/addtocart', - data: {productId: $(this).attr('data-id')} + data: { productId: $(this).attr('data-id') } }) .done(function(msg){ $('#cart-count').text(msg.totalCartItems); @@ -567,7 +567,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', 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){ showNotification(msg.message, 'success', true); @@ -581,7 +581,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', 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){ showNotification(msg.message, 'success', true); @@ -597,7 +597,7 @@ $(document).ready(function (){ $.ajax({ method: 'POST', url: '/admin/api/validate_permalink', - data: {'permalink': $('#frmProductPermalink').val(), 'docId': $('#frmProductId').val()} + data: { 'permalink': $('#frmProductPermalink').val(), 'docId': $('#frmProductId').val() } }) .done(function(msg){ showNotification(msg, 'success'); @@ -677,7 +677,7 @@ function deleteFromCart(element){ $.ajax({ method: 'POST', url: '/product/removefromcart', - data: {cartId: element.attr('data-id')} + data: { cartId: element.attr('data-id') } }) .done(function(msg){ $('#cart-count').text(msg.totalCartItems); @@ -740,7 +740,7 @@ function updateCart(){ $.ajax({ method: 'POST', url: '/product/updatecart', - data: {items: JSON.stringify(cartItems)} + data: { items: JSON.stringify(cartItems) } }) .done(function(msg){ // update cart items @@ -758,7 +758,7 @@ function updateCartDiv(){ $.ajax({ method: 'GET', url: '/cartPartial', - data: {path: path} + data: { path: path } }) .done(function(msg){ // update cart div diff --git a/routes/admin.js b/routes/admin.js index 753f31d..66f099c 100644 --- a/routes/admin.js +++ b/routes/admin.js @@ -1,5 +1,6 @@ const express = require('express'); const common = require('../lib/common'); +const { restrict, checkAccess } = require('../lib/auth'); const escape = require('html-entities').AllHtmlEntities; const colors = require('colors'); const bcrypt = require('bcryptjs'); @@ -12,7 +13,7 @@ const ObjectId = require('mongodb').ObjectID; const router = express.Router(); // Admin section -router.get('/admin', common.restrict, (req, res, next) => { +router.get('/admin', restrict, (req, res, next) => { res.redirect('/admin/orders'); }); @@ -59,15 +60,15 @@ router.get('/admin/login', (req, res) => { router.post('/admin/login_action', (req, res) => { 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){ - 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; } // check if user exists with that email 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{ // we have a user under that email so we compare the password 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.userId = user._id.toString(); req.session.isAdmin = user.isAdmin; - res.status(200).json({message: 'Login successful'}); + res.status(200).json({ message: 'Login successful' }); }else{ // 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 -router.get('/admin/settings', common.restrict, (req, res) => { +router.get('/admin/settings', restrict, (req, res) => { res.render('settings', { title: 'Cart settings', session: req.session, @@ -168,7 +169,7 @@ router.get('/admin/settings', common.restrict, (req, res) => { }); // 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; let result = await db.users.findOneAndUpdate({ _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){ - 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; } - res.status(400).json({message: 'Failed to generate API Key'}); + res.status(400).json({ message: 'Failed to generate API Key' }); }); // 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); if(result === true){ - res.status(200).json({message: 'Settings successfully updated'}); + res.status(200).json({ message: 'Settings successfully updated' }); res.configDirty = true; return; } - res.status(400).json({message: 'Permission denied'}); + res.status(400).json({ message: 'Permission denied' }); }); // 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; - db.products.findOne({_id: common.getId(req.body.productId)}, (err, product) => { + db.products.findOne({ _id: common.getId(req.body.productId) }, (err, product) => { if(err){ console.info(err.stack); } @@ -210,24 +211,24 @@ router.post('/admin/settings/option/remove', common.restrict, common.checkAccess let optJson = JSON.parse(product.productOptions); 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){ console.info(err.stack); } if(numReplaced.result.nModified === 1){ - res.status(200).json({message: 'Option successfully removed'}); + res.status(200).json({ message: 'Option successfully removed' }); }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{ - 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 -router.get('/admin/settings/menu', common.restrict, async (req, res) => { +router.get('/admin/settings/menu', restrict, async (req, res) => { const db = req.app.db; res.render('settings_menu', { title: 'Cart menu', @@ -242,7 +243,7 @@ router.get('/admin/settings/menu', common.restrict, async (req, res) => { }); // 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; db.pages.find({}).toArray(async (err, pages) => { if(err){ @@ -264,7 +265,7 @@ router.get('/admin/settings/pages', common.restrict, (req, res) => { }); // 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; res.render('settings_page_edit', { @@ -281,9 +282,9 @@ router.get('/admin/settings/pages/new', common.restrict, common.checkAccess, asy }); // 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; - 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){ console.info(err.stack); } @@ -317,7 +318,7 @@ router.get('/admin/settings/pages/edit/:page', common.restrict, common.checkAcce }); // 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; let doc = { @@ -329,37 +330,37 @@ router.post('/admin/settings/pages/update', common.restrict, common.checkAccess, if(req.body.page_id){ // 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){ console.info(err.stack); } 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){ 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{ - res.status(400).json({message: 'Page not found'}); + res.status(400).json({ message: 'Page not found' }); } }); }else{ // insert page db.pages.insert(doc, (err, newDoc) => { 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{ - 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 -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; - db.pages.remove({_id: common.getId(req.params.page)}, {}, (err, numRemoved) => { + db.pages.remove({ _id: common.getId(req.params.page) }, {}, (err, numRemoved) => { if(err){ req.session.message = 'Error deleting page. Please try again.'; req.session.messageType = 'danger'; @@ -373,7 +374,7 @@ router.get('/admin/settings/pages/delete/:page', common.restrict, common.checkAc }); // 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); if(result === false){ 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 -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); if(result === false){ req.session.message = 'Failed updating menu.'; @@ -393,7 +394,7 @@ router.post('/admin/settings/menu/update', common.restrict, common.checkAccess, }); // 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); if(result === false){ 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 -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); if(result === false){ - res.status(400).json({message: 'Failed saving menu order'}); + res.status(400).json({ message: 'Failed saving menu order' }); return; } res.status(200); @@ -420,9 +421,9 @@ router.post('/admin/api/validate_permalink', (req, res) => { let query = {}; if(typeof req.body.docId === 'undefined' || req.body.docId === ''){ - query = {productPermalink: req.body.permalink}; + query = { productPermalink: req.body.permalink }; }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) => { @@ -430,16 +431,16 @@ router.post('/admin/api/validate_permalink', (req, res) => { console.info(err.stack); } if(products > 0){ - res.status(400).json({message: 'Permalink already exists'}); + res.status(400).json({ message: 'Permalink already exists' }); }else{ - res.status(200).json({message: 'Permalink validated successfully'}); + res.status(200).json({ message: 'Permalink validated successfully' }); } }); }); // upload the file -let upload = multer({dest: 'public/uploads/'}); -router.post('/admin/file/upload', common.restrict, common.checkAccess, upload.single('upload_file'), (req, res, next) => { +let upload = multer({ dest: 'public/uploads/' }); +router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_file'), (req, res, next) => { const db = req.app.db; if(req.file){ @@ -461,7 +462,7 @@ router.post('/admin/file/upload', common.restrict, common.checkAccess, upload.si } // 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){ console.info(err.stack); // 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(!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){ 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 -router.post('/admin/testEmail', common.restrict, (req, res) => { +router.post('/admin/testEmail', restrict, (req, res) => { let config = req.app.config; // TODO: Should fix this to properly handle result 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 -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.messageType = null; fs.unlink('public/' + req.body.img, (err) => { if(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); }else{ - res.writeHead(200, {'Content-Type': 'application/text'}); + res.writeHead(200, { 'Content-Type': 'application/text' }); 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/ - glob('public/uploads/**', {nosort: true}, (er, files) => { + glob('public/uploads/**', { nosort: true }, (er, files) => { // sort array files.sort(); diff --git a/routes/customer.js b/routes/customer.js index c378f00..9b110b1 100644 --- a/routes/customer.js +++ b/routes/customer.js @@ -4,6 +4,7 @@ const colors = require('colors'); const randtoken = require('rand-token'); const bcrypt = require('bcryptjs'); const common = require('../lib/common'); +const { restrict } = require('../lib/auth'); // insert a customer router.post('/customer/create', (req, res) => { @@ -24,7 +25,7 @@ router.post('/customer/create', (req, res) => { }; // check for existing customer - db.customers.findOne({email: req.body.email}, (err, customer) => { + db.customers.findOne({ email: req.body.email }, (err, customer) => { if(customer){ res.status(400).json({ err: 'A customer already exists with that email address' @@ -59,10 +60,10 @@ router.post('/customer/create', (req, res) => { }); // 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; - db.customers.findOne({_id: common.getId(req.params.id)}, (err, result) => { + db.customers.findOne({ _id: common.getId(req.params.id) }, (err, result) => { if(err){ console.info(err.stack); } @@ -82,10 +83,10 @@ router.get('/admin/customer/view/:id?', common.restrict, (req, res) => { }); // customers list -router.get('/admin/customers', common.restrict, (req, res) => { +router.get('/admin/customers', restrict, (req, res) => { 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', { title: 'Customers - List', admin: true, @@ -100,7 +101,7 @@ router.get('/admin/customers', common.restrict, (req, res) => { }); // 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; let searchTerm = req.params.search; 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 - 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){ console.error(colors.red('Error searching', err)); } @@ -193,11 +194,11 @@ router.post('/customer/forgotten_action', (req, res) => { let passwordToken = randtoken.generate(30); // 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(customer){ 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 let mailOpts = { to: req.body.email, @@ -227,7 +228,7 @@ router.get('/customer/reset/:token', (req, res) => { const db = req.app.db; // 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){ req.session.message = 'Password reset token is invalid or has expired'; req.session.message_type = 'danger'; @@ -254,7 +255,7 @@ router.post('/customer/reset/:token', (req, res) => { const db = req.app.db; // 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){ req.session.message = 'Password reset token is invalid or has expired'; req.session.message_type = 'danger'; @@ -263,7 +264,7 @@ router.post('/customer/reset/:token', (req, res) => { // update the password and remove the token 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 = { to: customer.email, subject: 'Password successfully reset', diff --git a/routes/index.js b/routes/index.js index e5fb317..38212d0 100644 --- a/routes/index.js +++ b/routes/index.js @@ -11,7 +11,7 @@ router.get('/payment/:orderId', async (req, res, next) => { let config = req.app.config; // 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){ 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(config.trackStock && req.session.paymentApproved){ 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; if(newStockLevel < 1){ newStockLevel = 0; @@ -32,7 +32,7 @@ router.get('/payment/:orderId', async (req, res, next) => { $set: { productStock: newStockLevel } - }, {multi: false}); + }, { multi: false }); }); } @@ -122,13 +122,13 @@ router.get('/product/:id', (req, res) => { let db = req.app.db; 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 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'){ - 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{ let productOptions = {}; if(result.productOptions){ @@ -180,7 +180,7 @@ router.post('/product/updatecart', (req, res, next) => { req.session.cart.splice(cartItem.cartIndex, 1); callback(null); }else{ - db.products.findOne({_id: common.getId(cartItem.productId)}, (err, product) => { + db.products.findOne({ _id: common.getId(cartItem.productId) }, (err, product) => { if(err){ console.error(colors.red('Error updating cart', err)); } @@ -212,18 +212,18 @@ router.post('/product/updatecart', (req, res, next) => { common.updateTotalCartAmount(req, res); // Update cart to the DB - await db.cart.update({sessionId: req.session.id}, { - $set: {cart: req.session.cart} + await db.cart.update({ sessionId: req.session.id }, { + $set: { cart: req.session.cart } }); // show response 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{ 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{ - 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(); }, async () => { // Update cart in DB - await db.cart.update({sessionId: req.session.id}, { - $set: {cart: req.session.cart} + await db.cart.update({ sessionId: req.session.id }, { + $set: { cart: req.session.cart } }); // update total cart amount common.updateTotalCartAmount(req, res); 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; // Remove cart from DB - await db.cart.removeOne({sessionId: req.session.id}); + await db.cart.removeOne({ sessionId: req.session.id }); // update total cart amount 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 @@ -292,15 +292,15 @@ router.post('/product/addtocart', (req, res, next) => { } // 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){ 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 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 @@ -308,14 +308,14 @@ router.post('/product/addtocart', (req, res, next) => { const stockHeld = await db.cart.aggregate( { $match: { - cart: {$elemMatch: {productId: product._id.toString()}} + cart: { $elemMatch: { productId: product._id.toString() } } } }, - {$unwind: '$cart'}, + { $unwind: '$cart' }, { $group: { _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(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; // Check there is sufficient stock 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 - await db.cart.update({sessionId: req.session.id}, { - $set: {cart: req.session.cart} - }, {upsert: true}); + await db.cart.update({ sessionId: req.session.id }, { + $set: { cart: req.session.cart } + }, { upsert: true }); // update total cart amount common.updateTotalCartAmount(req, res); // update how many products in the shopping cart 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([ - common.getData(req, pageNum, {_id: {$in: lunrIdArray}}), + common.getData(req, pageNum, { _id: { $in: lunrIdArray } }), common.getMenu(db) ]) .then(([results, menu]) => { @@ -469,7 +469,7 @@ router.get('/category/:cat/:pageNum?', (req, res) => { } Promise.all([ - common.getData(req, pageNum, {_id: {$in: lunrIdArray}}), + common.getData(req, pageNum, { _id: { $in: lunrIdArray } }), common.getMenu(db) ]) .then(([results, menu]) => { @@ -521,7 +521,7 @@ router.get('/sitemap.xml', (req, res, next) => { hostname: config.baseUrl, cacheTime: 600000, urls: [ - {url: '/', changefreq: 'weekly', priority: 1.0} + { url: '/', changefreq: 'weekly', priority: 1.0 } ] }); @@ -625,7 +625,7 @@ router.get('/:page?', (req, res, next) => { return; } // 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){ console.error(colors.red('Error getting page', err)); } diff --git a/routes/order.js b/routes/order.js index 970aed4..b80a7c0 100644 --- a/routes/order.js +++ b/routes/order.js @@ -1,13 +1,14 @@ const express = require('express'); const common = require('../lib/common'); +const { restrict, checkAccess } = require('../lib/auth'); const router = express.Router(); // Show orders -router.get('/admin/orders', common.restrict, (req, res, next) => { +router.get('/admin/orders', restrict, (req, res, next) => { const db = req.app.db; // 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){ console.info(err.stack); } @@ -33,7 +34,7 @@ router.get('/admin/orders', common.restrict, (req, res, next) => { }); // 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; if(typeof req.params.orderstatus === 'undefined'){ @@ -43,7 +44,7 @@ router.get('/admin/orders/bystatus/:orderstatus', common.restrict, (req, res, ne // case insensitive search 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){ console.info(err.stack); } @@ -71,9 +72,9 @@ router.get('/admin/orders/bystatus/:orderstatus', common.restrict, (req, res, ne }); // 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; - db.orders.findOne({_id: common.getId(req.params.id)}, (err, result) => { + db.orders.findOne({ _id: common.getId(req.params.id) }, (err, result) => { if(err){ console.info(err.stack); } @@ -92,7 +93,7 @@ router.get('/admin/order/view/:id', common.restrict, (req, res) => { }); // 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; let searchTerm = req.params.search; 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 - db.orders.find({_id: {$in: lunrIdArray}}).toArray((err, orders) => { + db.orders.find({ _id: { $in: lunrIdArray } }).toArray((err, orders) => { if(err){ console.info(err.stack); } @@ -130,11 +131,11 @@ router.get('/admin/orders/filter/:search', common.restrict, (req, res, next) => }); // 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; // 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){ console.info(err.stack); } @@ -150,13 +151,13 @@ router.get('/admin/order/delete/:id', common.restrict, (req, res) => { }); // 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; - 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){ console.info(err.stack); } - res.status(200).json({message: 'Status successfully updated'}); + res.status(200).json({ message: 'Status successfully updated' }); }); }); diff --git a/routes/payments/paypal.js b/routes/payments/paypal.js index 6a660dc..ccfae35 100644 --- a/routes/payments/paypal.js +++ b/routes/payments/paypal.js @@ -14,7 +14,7 @@ router.get('/checkout_return', (req, res, next) => { let paymentId = req.session.paymentId; let payerId = req.query['PayerID']; - let details = {'payer_id': payerId}; + let details = { 'payer_id': payerId }; paypal.payment.execute(paymentId, details, (error, payment) => { let paymentApproved = false; let paymentMessage = ''; @@ -66,11 +66,11 @@ router.get('/checkout_return', (req, res, next) => { } // 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){ console.info(err.stack); } - db.orders.findOne({_id: common.getId(paymentOrderId)}, (err, order) => { + db.orders.findOne({ _id: common.getId(paymentOrderId) }, (err, order) => { if(err){ console.info(err.stack); } diff --git a/routes/product.js b/routes/product.js index ee7f483..ffeafd9 100644 --- a/routes/product.js +++ b/routes/product.js @@ -1,15 +1,16 @@ const express = require('express'); const common = require('../lib/common'); +const { restrict, checkAccess } = require('../lib/auth'); const colors = require('colors'); const rimraf = require('rimraf'); const fs = require('fs'); const path = require('path'); 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; // 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){ console.info(err.stack); } @@ -37,7 +38,7 @@ router.get('/admin/products/filter/:search', (req, res, next) => { }); // 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){ console.error(colors.red('Error searching', err)); } @@ -56,7 +57,7 @@ router.get('/admin/products/filter/:search', (req, res, next) => { }); // 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', { title: 'New product', session: req.session, @@ -74,7 +75,7 @@ router.get('/admin/product/new', common.restrict, common.checkAccess, (req, res) }); // 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; 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 }; - db.products.count({'productPermalink': req.body.frmProductPermalink}, (err, product) => { + db.products.count({ 'productPermalink': req.body.frmProductPermalink }, (err, product) => { if(err){ console.info(err.stack); } @@ -151,11 +152,11 @@ router.post('/admin/product/insert', common.restrict, common.checkAccess, (req, }); // 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; 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){ 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 -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; - db.products.findOne({_id: common.getId(req.body.frmProductId)}, (err, product) => { + db.products.findOne({ _id: common.getId(req.body.frmProductId) }, (err, product) => { if(err){ console.info(err.stack); 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); 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){ console.info(err.stack); req.session.message = 'Failed updating product.'; @@ -244,7 +245,7 @@ router.post('/admin/product/update', common.restrict, common.checkAccess, (req, 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){ console.error(colors.red('Failed to save product: ' + err)); 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 -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; // 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){ 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 -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; - 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){ console.error(colors.red('Failed to update the published state: ' + err)); 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 -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; // 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){ - 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{ - res.status(200).json({message: 'Main image successfully set'}); + res.status(200).json({ message: 'Main image successfully set' }); } }); }); // 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; // 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){ console.info(err.stack); } if(req.body.productImage === product.productImage){ // 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){ console.info(err.stack); } // remove the image from disk fs.unlink(path.join('public', req.body.productImage), (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{ - 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 fs.unlink(path.join('public', req.body.productImage), (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{ - res.status(200).json({message: 'Image successfully deleted'}); + res.status(200).json({ message: 'Image successfully deleted' }); } }); } diff --git a/routes/user.js b/routes/user.js index 2089266..5652a83 100644 --- a/routes/user.js +++ b/routes/user.js @@ -1,11 +1,12 @@ const express = require('express'); const common = require('../lib/common'); +const { restrict } = require('../lib/auth'); const colors = require('colors'); const bcrypt = require('bcryptjs'); const url = require('url'); const router = express.Router(); -router.get('/admin/users', common.restrict, (req, res) => { +router.get('/admin/users', restrict, (req, res) => { const db = req.app.db; db.users.find({}).toArray((err, users) => { if(err){ @@ -26,9 +27,9 @@ router.get('/admin/users', common.restrict, (req, res) => { }); // 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; - db.users.findOne({_id: common.getId(req.params.id)}, (err, user) => { + db.users.findOne({ _id: common.getId(req.params.id) }, (err, user) => { if(err){ console.info(err.stack); } @@ -55,7 +56,7 @@ router.get('/admin/user/edit/:id', common.restrict, (req, res) => { }); // users new -router.get('/admin/user/new', common.restrict, (req, res) => { +router.get('/admin/user/new', restrict, (req, res) => { res.render('user_new', { title: 'User - New', admin: true, @@ -68,10 +69,10 @@ router.get('/admin/user/new', common.restrict, (req, res) => { }); // 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; 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){ console.info(err.stack); } @@ -87,13 +88,13 @@ router.get('/admin/user/delete/:id', common.restrict, (req, res) => { }); // 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; let isAdmin = req.body.user_admin === 'on'; // 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){ console.info(err.stack); } @@ -120,10 +121,10 @@ router.post('/admin/user/update', common.restrict, (req, res) => { 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 - }, {multi: false}, (err, numReplaced) => { + }, { multi: false }, (err, numReplaced) => { if(err){ console.error(colors.red('Failed updating user: ' + err)); req.session.message = 'Failed to update user'; @@ -140,7 +141,7 @@ router.post('/admin/user/update', common.restrict, (req, res) => { }); // 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; // 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 - db.users.findOne({'userEmail': req.body.userEmail}, (err, user) => { + db.users.findOne({ 'userEmail': req.body.userEmail }, (err, user) => { if(user){ // user already exists with that email address console.error(colors.red('Failed to insert user, possibly already exists: ' + err)); diff --git a/test/test.js b/test/test.js index 8905c1c..e1b8617 100644 --- a/test/test.js +++ b/test/test.js @@ -2,7 +2,7 @@ const test = require('ava'); const fs = require('fs'); const _ = require('lodash'); const app = require('../app'); -const common = require('../lib/common'); +const { runIndexing, fixProductDates } = require('../lib/indexing'); const session = require('supertest-session'); // Get test data to compare in tests @@ -15,7 +15,6 @@ let config; let products; let customers; let users; -let orders; let request = null; function setup(db){ @@ -30,7 +29,7 @@ function setup(db){ return Promise.all([ db.users.insertMany(jsonData.users), 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; await setup(db); - await common.runIndexing(app); + await runIndexing(app); // Get some data from DB to use in compares products = await db.products.find({}).toArray(); @@ -70,8 +69,6 @@ test.before(async () => { await db.orders.insert(order); }); - // Get orders - orders = await db.orders.find({}).toArray(); resolve(); }); });