master
Mark Moffat 2019-07-12 17:36:34 +09:30
parent dad8f59d2c
commit 7af378a7bb
15 changed files with 205 additions and 912 deletions

4
app.js
View File

@ -224,7 +224,7 @@ handlebars = handlebars.create({
}); });
// session store // session store
let store = new MongoStore({ const store = new MongoStore({
uri: config.databaseConnectionString, uri: config.databaseConnectionString,
collection: 'sessions' collection: 'sessions'
}); });
@ -286,7 +286,7 @@ app.use('/authorizenet', authorizenet);
// catch 404 and forward to error handler // catch 404 and forward to error handler
app.use((req, res, next) => { app.use((req, res, next) => {
let err = new Error('Not Found'); const err = new Error('Not Found');
err.status = 404; err.status = 404;
next(err); next(err);
}); });

View File

@ -67,7 +67,7 @@ const checkLogin = async (req, res, next) => {
// Middleware to check for admin access for certain route // Middleware to check for admin access for certain route
const checkAccess = (req, res, next) => { const checkAccess = (req, res, next) => {
const routeCheck = _.find(restrictedRoutes, { 'route': req.route.path }); 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 the user is not an admin and route is restricted, show message and redirect to /admin
if(req.session.isAdmin === false && routeCheck){ if(req.session.isAdmin === false && routeCheck){

View File

@ -77,18 +77,18 @@ const showCartCloseBtn = (page) => {
// adds products to sitemap.xml // adds products to sitemap.xml
const addSitemapProducts = (req, res, cb) => { const addSitemapProducts = (req, res, cb) => {
let db = req.app.db; const db = req.app.db;
let config = getConfig(); const config = getConfig();
let hostname = config.baseUrl; const hostname = config.baseUrl;
db.products.find({ productPublished: 'true' }).toArray((err, products) => { db.products.find({ productPublished: 'true' }).toArray((err, products) => {
let posts = []; const posts = [];
if(err){ if(err){
cb(null, posts); cb(null, posts);
} }
async.eachSeries(products, (item, callback) => { async.eachSeries(products, (item, callback) => {
let post = {}; const post = {};
let url = item._id; let url = item._id;
if(item.productPermalink){ if(item.productPermalink){
url = item.productPermalink; url = item.productPermalink;
@ -114,7 +114,7 @@ const clearSessionValue = (session, sessionVar) => {
}; };
const updateTotalCartAmount = (req, res) => { const updateTotalCartAmount = (req, res) => {
let config = getConfig(); const config = getConfig();
req.session.totalCartAmount = 0; req.session.totalCartAmount = 0;
@ -148,7 +148,7 @@ const getThemes = () => {
}; };
const getImages = (dir, req, res, callback) => { const getImages = (dir, req, res, callback) => {
let db = req.app.db; const db = req.app.db;
db.products.findOne({ _id: getId(dir) }, (err, product) => { db.products.findOne({ _id: getId(dir) }, (err, product) => {
if(err){ if(err){
@ -161,14 +161,14 @@ const getImages = (dir, req, res, callback) => {
files.sort(); files.sort();
// declare the array of objects // declare the array of objects
let fileList = []; const fileList = [];
// loop these files // loop these files
for(let i = 0; i < files.length; i++){ for(let i = 0; i < files.length; i++){
// only want files // only want files
if(fs.lstatSync(files[i]).isDirectory() === false){ if(fs.lstatSync(files[i]).isDirectory() === false){
// declare the file object and set its values // declare the file object and set its values
let file = { const file = {
id: i, id: i,
path: files[i].substring(6) path: files[i].substring(6)
}; };
@ -219,7 +219,7 @@ const getConfig = () => {
}; };
const getPaymentConfig = () => { const getPaymentConfig = () => {
let siteConfig = getConfig(); const siteConfig = getConfig();
const gateConfigFile = path.join(__dirname, '../config', `${siteConfig.paymentGateway}.json`); const gateConfigFile = path.join(__dirname, '../config', `${siteConfig.paymentGateway}.json`);
let config = []; let config = [];
@ -228,7 +228,7 @@ const getPaymentConfig = () => {
} }
// If a local config we combine the objects. Local configs are .gitignored // If a local config we combine the objects. Local configs are .gitignored
let localConfig = path.join(__dirname, '../config', `${siteConfig.paymentGateway}-local.json`); const localConfig = path.join(__dirname, '../config', `${siteConfig.paymentGateway}-local.json`);
if(fs.existsSync(localConfig)){ if(fs.existsSync(localConfig)){
const localConfigObj = JSON.parse(fs.readFileSync(localConfig, 'utf8')); const localConfigObj = JSON.parse(fs.readFileSync(localConfig, 'utf8'));
config = Object.assign(config, localConfigObj); config = Object.assign(config, localConfigObj);
@ -238,7 +238,7 @@ const getPaymentConfig = () => {
}; };
const updateConfig = (fields) => { const updateConfig = (fields) => {
let settingsFile = getConfig(); const settingsFile = getConfig();
_.forEach(fields, (value, key) => { _.forEach(fields, (value, key) => {
settingsFile[key] = value; settingsFile[key] = value;
@ -246,11 +246,11 @@ const updateConfig = (fields) => {
settingsFile['customCss'] = escape.encode(uglifycss.processString(value)); settingsFile['customCss'] = escape.encode(uglifycss.processString(value));
} }
if(key === 'footerHtml_input'){ if(key === 'footerHtml_input'){
let footerHtml = typeof value !== 'undefined' || value === '' ? escape.encode(value) : ''; const footerHtml = typeof value !== 'undefined' || value === '' ? escape.encode(value) : '';
settingsFile['footerHtml'] = footerHtml; settingsFile['footerHtml'] = footerHtml;
} }
if(key === 'googleAnalytics_input'){ if(key === 'googleAnalytics_input'){
let googleAnalytics = typeof value !== 'undefined' ? escape.encode(value) : ''; const googleAnalytics = typeof value !== 'undefined' ? escape.encode(value) : '';
settingsFile['googleAnalytics'] = googleAnalytics; settingsFile['googleAnalytics'] = googleAnalytics;
} }
}); });
@ -337,7 +337,7 @@ const newMenu = (req, res) => {
menu = {}; menu = {};
menu.items = []; menu.items = [];
} }
let newNav = { const newNav = {
title: req.body.navMenu, title: req.body.navMenu,
link: req.body.navLink, link: req.body.navLink,
order: Object.keys(menu.items).length + 1 order: Object.keys(menu.items).length + 1
@ -378,7 +378,7 @@ const updateMenu = (req, res) => {
return 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]); const 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 })
@ -419,9 +419,9 @@ const orderMenu = (req, res) => {
}; };
const getEmailTemplate = (result) => { const getEmailTemplate = (result) => {
let config = getConfig(); const config = getConfig();
let template = fs.readFileSync(path.join(__dirname, '../public/email_template.html'), 'utf8'); const template = fs.readFileSync(path.join(__dirname, '../public/email_template.html'), 'utf8');
$ = cheerio.load(template); $ = cheerio.load(template);
$('#brand').text(config.cartTitle); $('#brand').text(config.cartTitle);
@ -438,9 +438,9 @@ const getEmailTemplate = (result) => {
}; };
const sendEmail = (to, subject, body) => { const sendEmail = (to, subject, body) => {
let config = getConfig(); const config = getConfig();
let emailSettings = { const emailSettings = {
host: config.emailHost, host: config.emailHost,
port: config.emailPort, port: config.emailPort,
secure: config.emailSecure, secure: config.emailSecure,
@ -455,9 +455,9 @@ const sendEmail = (to, subject, body) => {
emailSettings.tls = { ciphers: 'SSLv3' }; emailSettings.tls = { ciphers: 'SSLv3' };
} }
let transporter = nodemailer.createTransport(emailSettings); const transporter = nodemailer.createTransport(emailSettings);
let mailOptions = { const mailOptions = {
from: config.emailAddress, // sender address from: config.emailAddress, // sender address
to: to, // list of receivers to: to, // list of receivers
subject: subject, // Subject line subject: subject, // Subject line
@ -483,9 +483,9 @@ const getId = (id) => {
}; };
const getData = (req, page, query) => { const getData = (req, page, query) => {
let db = req.app.db; const db = req.app.db;
let config = getConfig(); const config = getConfig();
let numberProducts = config.productsPerPage ? config.productsPerPage : 6; const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let skip = 0; let skip = 0;
if(page > 1){ if(page > 1){
@ -513,7 +513,7 @@ const getData = (req, page, query) => {
}; };
const hooker = (order) => { const hooker = (order) => {
let config = getConfig(); const config = getConfig();
return axios.post(config.orderHook, order, { responseType: 'application/json' }) return axios.post(config.orderHook, order, { responseType: 'application/json' })
.then((response) => { .then((response) => {

View File

@ -20,11 +20,11 @@ const indexProducts = (app) => {
// add to lunr index // add to lunr index
productsList.forEach((product) => { productsList.forEach((product) => {
let doc = { const doc = {
'productTitle': product.productTitle, productTitle: product.productTitle,
'productTags': product.productTags, productTags: product.productTags,
'productDescription': product.productDescription, productDescription: product.productDescription,
'id': product._id id: product._id
}; };
lunrIndex.add(doc); lunrIndex.add(doc);
}); });
@ -56,11 +56,11 @@ const indexCustomers = (app) => {
// add to lunr index // add to lunr index
customerList.forEach((customer) => { customerList.forEach((customer) => {
let doc = { const doc = {
'email': customer.email, email: customer.email,
'name': `${customer.firstName} ${customer.lastName}`, name: `${customer.firstName} ${customer.lastName}`,
'phone': customer.phone, phone: customer.phone,
'id': customer._id id: customer._id
}; };
lunrIndex.add(doc); lunrIndex.add(doc);
}); });
@ -92,11 +92,11 @@ const indexOrders = (app, cb) => {
// add to lunr index // add to lunr index
ordersList.forEach((order) => { ordersList.forEach((order) => {
let doc = { const doc = {
'orderLastname': order.orderLastname, orderLastname: order.orderLastname,
'orderEmail': order.orderEmail, orderEmail: order.orderEmail,
'orderPostcode': order.orderPostcode, orderPostcode: order.orderPostcode,
'id': order._id id: order._id
}; };
lunrIndex.add(doc); lunrIndex.add(doc);
}); });

View File

@ -8,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 = getConfig(); const config = getConfig();
initDb(config.databaseConnectionString, (err, db) => { initDb(config.databaseConnectionString, (err, db) => {
Promise.all([ Promise.all([

772
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -27,7 +27,7 @@ router.get('/admin/logout', (req, res) => {
// login form // login form
router.get('/admin/login', (req, res) => { router.get('/admin/login', (req, res) => {
let db = req.app.db; const db = req.app.db;
db.users.count({}, (err, userCount) => { db.users.count({}, (err, userCount) => {
if(err){ if(err){
@ -58,7 +58,7 @@ router.get('/admin/login', (req, res) => {
// login the user and check the password // login the user and check the password
router.post('/admin/login_action', (req, res) => { router.post('/admin/login_action', (req, res) => {
let db = req.app.db; const 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){
@ -90,7 +90,7 @@ router.post('/admin/login_action', (req, res) => {
// setup form is shown when there are no users setup in the DB // setup form is shown when there are no users setup in the DB
router.get('/admin/setup', (req, res) => { router.get('/admin/setup', (req, res) => {
let db = req.app.db; const db = req.app.db;
db.users.count({}, (err, userCount) => { db.users.count({}, (err, userCount) => {
if(err){ if(err){
@ -119,7 +119,7 @@ router.get('/admin/setup', (req, res) => {
router.post('/admin/setup_action', (req, res) => { router.post('/admin/setup_action', (req, res) => {
const db = req.app.db; const db = req.app.db;
let doc = { const doc = {
usersName: req.body.usersName, usersName: req.body.usersName,
userEmail: req.body.userEmail, userEmail: req.body.userEmail,
userPassword: bcrypt.hashSync(req.body.userPassword, 10), userPassword: bcrypt.hashSync(req.body.userPassword, 10),
@ -171,7 +171,7 @@ router.get('/admin/settings', restrict, (req, res) => {
// settings update // settings update
router.post('/admin/createApiKey', restrict, 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({ const result = await db.users.findOneAndUpdate({
_id: ObjectId(req.session.userId), _id: ObjectId(req.session.userId),
isAdmin: true isAdmin: true
}, { }, {
@ -208,7 +208,7 @@ router.post('/admin/settings/option/remove', restrict, checkAccess, (req, res) =
console.info(err.stack); console.info(err.stack);
} }
if(product && product.productOptions){ if(product && product.productOptions){
let optJson = JSON.parse(product.productOptions); const 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) => {
@ -321,7 +321,7 @@ router.get('/admin/settings/pages/edit/:page', restrict, checkAccess, (req, res)
router.post('/admin/settings/pages/update', restrict, 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 = { const doc = {
pageName: req.body.pageName, pageName: req.body.pageName,
pageSlug: req.body.pageSlug, pageSlug: req.body.pageSlug,
pageEnabled: req.body.pageEnabled, pageEnabled: req.body.pageEnabled,
@ -375,7 +375,7 @@ router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, (req, re
// new menu item // new menu item
router.post('/admin/settings/menu/new', restrict, checkAccess, (req, res) => { router.post('/admin/settings/menu/new', restrict, checkAccess, (req, res) => {
let result = common.newMenu(req, res); const result = common.newMenu(req, res);
if(result === false){ if(result === false){
req.session.message = 'Failed creating menu.'; req.session.message = 'Failed creating menu.';
req.session.messageType = 'danger'; req.session.messageType = 'danger';
@ -385,7 +385,7 @@ router.post('/admin/settings/menu/new', restrict, checkAccess, (req, res) => {
// update existing menu item // update existing menu item
router.post('/admin/settings/menu/update', restrict, checkAccess, (req, res) => { router.post('/admin/settings/menu/update', restrict, checkAccess, (req, res) => {
let result = common.updateMenu(req, res); const result = common.updateMenu(req, res);
if(result === false){ if(result === false){
req.session.message = 'Failed updating menu.'; req.session.message = 'Failed updating menu.';
req.session.messageType = 'danger'; req.session.messageType = 'danger';
@ -395,7 +395,7 @@ router.post('/admin/settings/menu/update', restrict, checkAccess, (req, res) =>
// delete menu item // delete menu item
router.get('/admin/settings/menu/delete/:menuid', restrict, checkAccess, (req, res) => { router.get('/admin/settings/menu/delete/:menuid', restrict, checkAccess, (req, res) => {
let result = common.deleteMenu(req, res, req.params.menuid); const 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.';
req.session.messageType = 'danger'; req.session.messageType = 'danger';
@ -405,7 +405,7 @@ router.get('/admin/settings/menu/delete/:menuid', restrict, checkAccess, (req, r
// 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', restrict, checkAccess, (req, res) => { router.post('/admin/settings/menu/save_order', restrict, checkAccess, (req, res) => {
let result = common.orderMenu(req, res); const 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;
@ -439,12 +439,12 @@ router.post('/admin/api/validate_permalink', (req, res) => {
}); });
// upload the file // upload the file
let upload = multer({ dest: 'public/uploads/' }); const upload = multer({ dest: 'public/uploads/' });
router.post('/admin/file/upload', restrict, 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){
let file = req.file; const file = req.file;
// Get the mime type of the file // Get the mime type of the file
const mimeType = mime.lookup(file.originalname); const mimeType = mime.lookup(file.originalname);
@ -476,13 +476,13 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
} }
const productPath = product.productPermalink; const productPath = product.productPermalink;
let uploadDir = path.join('public/uploads', productPath); const uploadDir = path.join('public/uploads', productPath);
// Check directory and create (if needed) // Check directory and create (if needed)
common.checkDirectorySync(uploadDir); common.checkDirectorySync(uploadDir);
let source = fs.createReadStream(file.path); const source = fs.createReadStream(file.path);
let dest = fs.createWriteStream(path.join(uploadDir, file.originalname.replace(/ /g, '_'))); const dest = fs.createWriteStream(path.join(uploadDir, file.originalname.replace(/ /g, '_')));
// save the new file // save the new file
source.pipe(dest); source.pipe(dest);
@ -491,7 +491,7 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
// delete the temp file. // delete the temp file.
fs.unlinkSync(file.path); fs.unlinkSync(file.path);
let imagePath = path.join('/uploads', productPath, file.originalname.replace(/ /g, '_')); const imagePath = path.join('/uploads', productPath, file.originalname.replace(/ /g, '_'));
// 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){
@ -519,7 +519,7 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
// delete a file via ajax request // delete a file via ajax request
router.post('/admin/testEmail', restrict, (req, res) => { router.post('/admin/testEmail', restrict, (req, res) => {
let config = req.app.config; const 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' });
@ -549,15 +549,15 @@ router.get('/admin/files', restrict, (req, res) => {
files.sort(); files.sort();
// declare the array of objects // declare the array of objects
let fileList = []; const fileList = [];
let dirList = []; const dirList = [];
// loop these files // loop these files
for(let i = 0; i < files.length; i++){ for(let i = 0; i < files.length; i++){
// only want files // only want files
if(fs.lstatSync(files[i]).isDirectory() === false){ if(fs.lstatSync(files[i]).isDirectory() === false){
// declare the file object and set its values // declare the file object and set its values
let file = { const file = {
id: i, id: i,
path: files[i].substring(6) path: files[i].substring(6)
}; };
@ -565,7 +565,7 @@ router.get('/admin/files', restrict, (req, res) => {
// push the file object into the array // push the file object into the array
fileList.push(file); fileList.push(file);
}else{ }else{
let dir = { const dir = {
id: i, id: i,
path: files[i].substring(6) path: files[i].substring(6)
}; };

View File

@ -10,7 +10,7 @@ const { restrict } = require('../lib/auth');
router.post('/customer/create', (req, res) => { router.post('/customer/create', (req, res) => {
const db = req.app.db; const db = req.app.db;
let doc = { const doc = {
email: req.body.email, email: req.body.email,
firstName: req.body.firstName, firstName: req.body.firstName,
lastName: req.body.lastName, lastName: req.body.lastName,
@ -113,10 +113,10 @@ router.get('/admin/customers', restrict, (req, res) => {
// Filtered customers list // Filtered customers list
router.get('/admin/customers/filter/:search', 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; const searchTerm = req.params.search;
let customersIndex = req.app.customersIndex; const customersIndex = req.app.customersIndex;
let lunrIdArray = []; const lunrIdArray = [];
customersIndex.search(searchTerm).forEach((id) => { customersIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(common.getId(id.ref)); lunrIdArray.push(common.getId(id.ref));
}); });
@ -150,7 +150,7 @@ router.get('/admin/customers/filter/:search', restrict, (req, res, next) => {
// login the customer and check the password // login the customer and check the password
router.post('/customer/login_action', async (req, res) => { router.post('/customer/login_action', async (req, res) => {
let db = req.app.db; const db = req.app.db;
db.customers.findOne({email: common.mongoSanitize(req.body.loginEmail)}, (err, customer) => { // eslint-disable-line db.customers.findOne({email: common.mongoSanitize(req.body.loginEmail)}, (err, customer) => { // eslint-disable-line
if(err){ if(err){
@ -209,16 +209,16 @@ router.get('/customer/forgotten', (req, res) => {
router.post('/customer/forgotten_action', (req, res) => { router.post('/customer/forgotten_action', (req, res) => {
const db = req.app.db; const db = req.app.db;
const config = req.app.config; const config = req.app.config;
let passwordToken = randtoken.generate(30); const 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; const 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 = { const mailOpts = {
to: req.body.email, to: req.body.email,
subject: 'Forgotten password request', subject: 'Forgotten password request',
body: `You are receiving this because you (or someone else) have requested the reset of the password for your user account.\n\n body: `You are receiving this because you (or someone else) have requested the reset of the password for your user account.\n\n
@ -281,9 +281,9 @@ 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); const 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 = { const mailOpts = {
to: customer.email, to: customer.email,
subject: 'Password successfully reset', subject: 'Password successfully reset',
body: 'This is a confirmation that the password for your account ' + customer.email + ' has just been changed successfully.\n' body: 'This is a confirmation that the password for your account ' + customer.email + ' has just been changed successfully.\n'

View File

@ -19,8 +19,8 @@ const {
// These is the customer facing routes // These is the customer facing routes
router.get('/payment/:orderId', async (req, res, next) => { router.get('/payment/:orderId', async (req, res, next) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
// render the payment complete message // render the payment complete message
db.orders.findOne({ _id: getId(req.params.orderId) }, async (err, order) => { db.orders.findOne({ _id: getId(req.params.orderId) }, async (err, order) => {
@ -69,7 +69,7 @@ router.get('/payment/:orderId', async (req, res, next) => {
}); });
router.get('/checkout', async (req, res, next) => { router.get('/checkout', async (req, res, next) => {
let config = req.app.config; const config = req.app.config;
// if there is no items in the cart then render a failure // if there is no items in the cart then render a failure
if(!req.session.cart){ if(!req.session.cart){
@ -136,8 +136,8 @@ router.get('/cartPartial', (req, res) => {
// show an individual product // show an individual product
router.get('/product/:id', (req, res) => { router.get('/product/:id', (req, res) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
db.products.findOne({ $or: [{ _id: getId(req.params.id) }, { productPermalink: req.params.id }] }, (err, result) => { db.products.findOne({ $or: [{ _id: getId(req.params.id) }, { productPermalink: req.params.id }] }, (err, result) => {
// render 404 if page is not published // render 404 if page is not published
@ -147,7 +147,7 @@ router.get('/product/:id', (req, res) => {
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 = result.productOptions; const productOptions = result.productOptions;
// If JSON query param return json instead // If JSON query param return json instead
if(req.query.json === 'true'){ if(req.query.json === 'true'){
@ -183,12 +183,12 @@ router.get('/product/:id', (req, res) => {
router.post('/product/updatecart', (req, res, next) => { router.post('/product/updatecart', (req, res, next) => {
const db = req.app.db; const db = req.app.db;
const config = req.app.config; const config = req.app.config;
let cartItems = JSON.parse(req.body.items); const cartItems = JSON.parse(req.body.items);
let hasError = false; let hasError = false;
let stockError = false; let stockError = false;
async.eachSeries(cartItems, (cartItem, callback) => { async.eachSeries(cartItems, (cartItem, callback) => {
let productQuantity = cartItem.itemQuantity ? cartItem.itemQuantity : 1; const productQuantity = cartItem.itemQuantity ? cartItem.itemQuantity : 1;
if(cartItem.itemQuantity === 0){ if(cartItem.itemQuantity === 0){
// quantity equals zero so we remove the item // quantity equals zero so we remove the item
req.session.cart.splice(cartItem.cartIndex, 1); req.session.cart.splice(cartItem.cartIndex, 1);
@ -209,7 +209,7 @@ router.post('/product/updatecart', (req, res, next) => {
} }
} }
let productPrice = parseFloat(product.productPrice).toFixed(2); const productPrice = parseFloat(product.productPrice).toFixed(2);
if(req.session.cart[cartItem.cartIndex]){ if(req.session.cart[cartItem.cartIndex]){
req.session.cart[cartItem.cartIndex].quantity = productQuantity; req.session.cart[cartItem.cartIndex].quantity = productQuantity;
req.session.cart[cartItem.cartIndex].totalItemPrice = productPrice * productQuantity; req.session.cart[cartItem.cartIndex].totalItemPrice = productPrice * productQuantity;
@ -351,20 +351,20 @@ router.post('/product/addtocart', (req, res, next) => {
} }
} }
let productPrice = parseFloat(product.productPrice).toFixed(2); const productPrice = parseFloat(product.productPrice).toFixed(2);
// Doc used to test if existing in the cart with the options. If not found, we add new. // Doc used to test if existing in the cart with the options. If not found, we add new.
let options = {}; let options = {};
if(req.body.productOptions){ if(req.body.productOptions){
options = JSON.parse(req.body.productOptions); options = JSON.parse(req.body.productOptions);
} }
let findDoc = { const findDoc = {
productId: req.body.productId, productId: req.body.productId,
options: options options: options
}; };
// if exists we add to the existing value // if exists we add to the existing value
let cartIndex = _.findIndex(req.session.cart, findDoc); const cartIndex = _.findIndex(req.session.cart, findDoc);
let cartQuantity = 0; let cartQuantity = 0;
if(cartIndex > -1){ if(cartIndex > -1){
cartQuantity = parseInt(req.session.cart[cartIndex].quantity) + productQuantity; cartQuantity = parseInt(req.session.cart[cartIndex].quantity) + productQuantity;
@ -378,7 +378,7 @@ router.post('/product/addtocart', (req, res, next) => {
cartQuantity = productQuantity; cartQuantity = productQuantity;
// new product deets // new product deets
let productObj = {}; const productObj = {};
productObj.productId = req.body.productId; productObj.productId = req.body.productId;
productObj.title = product.productTitle; productObj.title = product.productTitle;
productObj.quantity = productQuantity; productObj.quantity = productQuantity;
@ -412,13 +412,13 @@ router.post('/product/addtocart', (req, res, next) => {
// search products // search products
router.get('/search/:searchTerm/:pageNum?', (req, res) => { router.get('/search/:searchTerm/:pageNum?', (req, res) => {
let db = req.app.db; const db = req.app.db;
let searchTerm = req.params.searchTerm; const searchTerm = req.params.searchTerm;
let productsIndex = req.app.productsIndex; const productsIndex = req.app.productsIndex;
let config = req.app.config; const config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6; const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let lunrIdArray = []; const lunrIdArray = [];
productsIndex.search(searchTerm).forEach((id) => { productsIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(getId(id.ref)); lunrIdArray.push(getId(id.ref));
}); });
@ -466,13 +466,13 @@ router.get('/search/:searchTerm/:pageNum?', (req, res) => {
// search products // search products
router.get('/category/:cat/:pageNum?', (req, res) => { router.get('/category/:cat/:pageNum?', (req, res) => {
let db = req.app.db; const db = req.app.db;
let searchTerm = req.params.cat; const searchTerm = req.params.cat;
let productsIndex = req.app.productsIndex; const productsIndex = req.app.productsIndex;
let config = req.app.config; const config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6; const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let lunrIdArray = []; const lunrIdArray = [];
productsIndex.search(searchTerm).forEach((id) => { productsIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(getId(id.ref)); lunrIdArray.push(getId(id.ref));
}); });
@ -523,14 +523,14 @@ router.get('/category/:cat/:pageNum?', (req, res) => {
// return sitemap // return sitemap
router.get('/sitemap.xml', (req, res, next) => { router.get('/sitemap.xml', (req, res, next) => {
let sm = require('sitemap'); const sm = require('sitemap');
let config = req.app.config; const config = req.app.config;
addSitemapProducts(req, res, (err, products) => { addSitemapProducts(req, res, (err, products) => {
if(err){ if(err){
console.error(colors.red('Error generating sitemap.xml', err)); console.error(colors.red('Error generating sitemap.xml', err));
} }
let sitemap = sm.createSitemap( const sitemap = sm.createSitemap(
{ {
hostname: config.baseUrl, hostname: config.baseUrl,
cacheTime: 600000, cacheTime: 600000,
@ -539,8 +539,8 @@ router.get('/sitemap.xml', (req, res, next) => {
] ]
}); });
let currentUrls = sitemap.urls; const currentUrls = sitemap.urls;
let mergedUrls = currentUrls.concat(products); const mergedUrls = currentUrls.concat(products);
sitemap.urls = mergedUrls; sitemap.urls = mergedUrls;
// render the sitemap // render the sitemap
sitemap.toXML((err, xml) => { sitemap.toXML((err, xml) => {
@ -555,9 +555,9 @@ router.get('/sitemap.xml', (req, res, next) => {
}); });
router.get('/page/:pageNum', (req, res, next) => { router.get('/page/:pageNum', (req, res, next) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6; const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
Promise.all([ Promise.all([
getData(req, req.params.pageNum), getData(req, req.params.pageNum),
@ -595,9 +595,9 @@ router.get('/page/:pageNum', (req, res, next) => {
// The main entry point of the shop // The main entry point of the shop
router.get('/:page?', (req, res, next) => { router.get('/:page?', (req, res, next) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6; const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
// if no page is specified, just render page 1 of the cart // if no page is specified, just render page 1 of the cart
if(!req.params.page){ if(!req.params.page){

View File

@ -55,7 +55,7 @@ router.post('/checkout_action', (req, res, next) => {
orderStatus = 'Declined'; orderStatus = 'Declined';
} }
let orderDoc = { const orderDoc = {
orderPaymentId: txn.transHash, orderPaymentId: txn.transHash,
orderPaymentGateway: 'AuthorizeNet', orderPaymentGateway: 'AuthorizeNet',
orderPaymentMessage: 'Your payment was successfully completed', orderPaymentMessage: 'Your payment was successfully completed',
@ -82,7 +82,7 @@ router.post('/checkout_action', (req, res, next) => {
} }
// get the new ID // get the new ID
let newId = newDoc.insertedIds['0']; const newId = newDoc.insertedIds['0'];
// add to lunr index // add to lunr index
indexOrders(req.app) indexOrders(req.app)
@ -98,7 +98,7 @@ router.post('/checkout_action', (req, res, next) => {
<p><strong>Transaction ID: </strong>${txn.transHash}</p>`; <p><strong>Transaction ID: </strong>${txn.transHash}</p>`;
// set payment results for email // set payment results for email
let paymentResults = { const paymentResults = {
message: req.session.message, message: req.session.message,
messageType: req.session.messageType, messageType: req.session.messageType,
paymentEmailAddr: req.session.paymentEmailAddr, paymentEmailAddr: req.session.paymentEmailAddr,

View File

@ -1,8 +1,8 @@
let express = require('express'); const express = require('express');
let common = require('../../lib/common'); const common = require('../../lib/common');
const { indexOrders } = require('../../lib/indexing'); const { indexOrders } = require('../../lib/indexing');
let paypal = require('paypal-rest-sdk'); const paypal = require('paypal-rest-sdk');
let router = express.Router(); const router = express.Router();
router.get('/checkout_cancel', (req, res, next) => { router.get('/checkout_cancel', (req, res, next) => {
// return to checkout for adjustment or repayment // return to checkout for adjustment or repayment
@ -10,12 +10,12 @@ router.get('/checkout_cancel', (req, res, next) => {
}); });
router.get('/checkout_return', (req, res, next) => { router.get('/checkout_return', (req, res, next) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
let paymentId = req.session.paymentId; const paymentId = req.session.paymentId;
let payerId = req.query['PayerID']; const payerId = req.query['PayerID'];
let details = { 'payer_id': payerId }; const 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 = '';
@ -41,7 +41,7 @@ router.get('/checkout_return', (req, res, next) => {
return; return;
} }
let paymentOrderId = req.session.orderId; const paymentOrderId = req.session.orderId;
let paymentStatus = 'Approved'; let paymentStatus = 'Approved';
// fully approved // fully approved
@ -86,7 +86,7 @@ router.get('/checkout_return', (req, res, next) => {
req.session.paymentApproved = paymentApproved; req.session.paymentApproved = paymentApproved;
req.session.paymentDetails = paymentDetails; req.session.paymentDetails = paymentDetails;
let paymentResults = { const paymentResults = {
message: req.session.message, message: req.session.message,
messageType: req.session.messageType, messageType: req.session.messageType,
paymentEmailAddr: req.session.paymentEmailAddr, paymentEmailAddr: req.session.paymentEmailAddr,
@ -107,26 +107,26 @@ router.get('/checkout_return', (req, res, next) => {
// The homepage of the site // The homepage of the site
router.post('/checkout_action', (req, res, next) => { router.post('/checkout_action', (req, res, next) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
let paypalConfig = common.getPaymentConfig(); const paypalConfig = common.getPaymentConfig();
// setup the payment object // setup the payment object
let payment = { const payment = {
'intent': 'sale', intent: 'sale',
'payer': { payer: {
'payment_method': 'paypal' payment_method: 'paypal'
}, },
'redirect_urls': { redirect_urls: {
'return_url': config.baseUrl + '/paypal/checkout_return', return_url: config.baseUrl + '/paypal/checkout_return',
'cancel_url': config.baseUrl + '/paypal/checkout_cancel' cancel_url: config.baseUrl + '/paypal/checkout_cancel'
}, },
'transactions': [{ transactions: [{
'amount': { amount: {
'total': req.session.totalCartAmount, total: req.session.totalCartAmount,
'currency': paypalConfig.paypalCurrency currency: paypalConfig.paypalCurrency
}, },
'description': paypalConfig.paypalCartDescription description: paypalConfig.paypalCartDescription
}] }]
}; };
@ -145,7 +145,7 @@ router.post('/checkout_action', (req, res, next) => {
req.session.paymentId = payment.id; req.session.paymentId = payment.id;
let redirectUrl; let redirectUrl;
for(let i = 0; i < payment.links.length; i++){ for(let i = 0; i < payment.links.length; i++){
let link = payment.links[i]; const link = payment.links[i];
if(link.method === 'REDIRECT'){ if(link.method === 'REDIRECT'){
redirectUrl = link.href; redirectUrl = link.href;
} }
@ -160,7 +160,7 @@ router.post('/checkout_action', (req, res, next) => {
} }
// new order doc // new order doc
let orderDoc = { const orderDoc = {
orderPaymentId: payment.id, orderPaymentId: payment.id,
orderPaymentGateway: 'Paypal', orderPaymentGateway: 'Paypal',
orderTotal: req.session.totalCartAmount, orderTotal: req.session.totalCartAmount,
@ -192,7 +192,7 @@ router.post('/checkout_action', (req, res, next) => {
} }
// get the new ID // get the new ID
let newId = newDoc.insertedIds['0']; const newId = newDoc.insertedIds['0'];
// set the order ID in the session // set the order ID in the session
req.session.orderId = newId; req.session.orderId = newId;

View File

@ -1,15 +1,15 @@
let express = require('express'); const express = require('express');
let common = require('../../lib/common'); const common = require('../../lib/common');
const { indexOrders } = require('../../lib/indexing'); const { indexOrders } = require('../../lib/indexing');
let numeral = require('numeral'); const numeral = require('numeral');
let stripe = require('stripe')(common.getPaymentConfig().secretKey); const stripe = require('stripe')(common.getPaymentConfig().secretKey);
let router = express.Router(); const router = express.Router();
// The homepage of the site // The homepage of the site
router.post('/checkout_action', (req, res, next) => { router.post('/checkout_action', (req, res, next) => {
let db = req.app.db; const db = req.app.db;
let config = req.app.config; const config = req.app.config;
let stripeConfig = common.getPaymentConfig(); const stripeConfig = common.getPaymentConfig();
// charge via stripe // charge via stripe
stripe.charges.create({ stripe.charges.create({
@ -35,7 +35,7 @@ router.post('/checkout_action', (req, res, next) => {
} }
// new order doc // new order doc
let orderDoc = { const orderDoc = {
orderPaymentId: charge.id, orderPaymentId: charge.id,
orderPaymentGateway: 'Stripe', orderPaymentGateway: 'Stripe',
orderPaymentMessage: charge.outcome.seller_message, orderPaymentMessage: charge.outcome.seller_message,
@ -62,7 +62,7 @@ router.post('/checkout_action', (req, res, next) => {
} }
// get the new ID // get the new ID
let newId = newDoc.insertedIds['0']; const newId = newDoc.insertedIds['0'];
// add to lunr index // add to lunr index
indexOrders(req.app) indexOrders(req.app)
@ -77,7 +77,7 @@ router.post('/checkout_action', (req, res, next) => {
req.session.paymentDetails = '<p><strong>Order ID: </strong>' + newId + '</p><p><strong>Transaction ID: </strong>' + charge.id + '</p>'; req.session.paymentDetails = '<p><strong>Order ID: </strong>' + newId + '</p><p><strong>Transaction ID: </strong>' + charge.id + '</p>';
// set payment results for email // set payment results for email
let paymentResults = { const paymentResults = {
message: req.session.message, message: req.session.message,
messageType: req.session.messageType, messageType: req.session.messageType,
paymentEmailAddr: req.session.paymentEmailAddr, paymentEmailAddr: req.session.paymentEmailAddr,

View File

@ -12,7 +12,7 @@ const router = express.Router();
router.get('/admin/products', 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);
} }
@ -31,10 +31,10 @@ router.get('/admin/products', restrict, (req, res, next) => {
router.get('/admin/products/filter/:search', (req, res, next) => { router.get('/admin/products/filter/:search', (req, res, next) => {
const db = req.app.db; const db = req.app.db;
let searchTerm = req.params.search; const searchTerm = req.params.search;
let productsIndex = req.app.productsIndex; const productsIndex = req.app.productsIndex;
let lunrIdArray = []; const lunrIdArray = [];
productsIndex.search(searchTerm).forEach((id) => { productsIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(common.getId(id.ref)); lunrIdArray.push(common.getId(id.ref));
}); });
@ -90,7 +90,7 @@ router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
} }
} }
let doc = { const doc = {
productPermalink: req.body.productPermalink, productPermalink: req.body.productPermalink,
productTitle: common.cleanHtml(req.body.productTitle), productTitle: common.cleanHtml(req.body.productTitle),
productPrice: common.safeParseInt(req.body.productPrice), productPrice: common.safeParseInt(req.body.productPrice),
@ -131,7 +131,7 @@ router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
return; return;
} }
db.products.count({ 'productPermalink': req.body.productPermalink }, (err, product) => { db.products.count({ productPermalink: req.body.productPermalink }, (err, product) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
} }
@ -188,7 +188,7 @@ router.post('/admin/product/insert', restrict, checkAccess, (req, res) => {
return; return;
} }
// get the new ID // get the new ID
let newId = newDoc.insertedIds[0]; const newId = newDoc.insertedIds[0];
// add to lunr index // add to lunr index
indexProducts(req.app) indexProducts(req.app)
@ -259,7 +259,7 @@ router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
res.redirect('/admin/product/edit/' + req.body.productId); res.redirect('/admin/product/edit/' + req.body.productId);
return; return;
} }
db.products.count({ 'productPermalink': req.body.productPermalink, _id: { $ne: common.getId(product._id) } }, (err, count) => { db.products.count({ productPermalink: req.body.productPermalink, _id: { $ne: common.getId(product._id) } }, (err, count) => {
if(err){ if(err){
console.info(err.stack); console.info(err.stack);
@ -310,7 +310,7 @@ router.post('/admin/product/update', restrict, checkAccess, (req, res) => {
} }
} }
let productDoc = { const productDoc = {
productId: req.body.productId, productId: req.body.productId,
productPermalink: req.body.productPermalink, productPermalink: req.body.productPermalink,
productTitle: common.cleanHtml(req.body.productTitle), productTitle: common.cleanHtml(req.body.productTitle),

View File

@ -3,7 +3,6 @@ const common = require('../lib/common');
const { restrict } = require('../lib/auth'); 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 router = express.Router(); const router = express.Router();
router.get('/admin/users', restrict, (req, res) => { router.get('/admin/users', restrict, (req, res) => {
@ -114,7 +113,7 @@ router.post('/admin/user/update', restrict, (req, res) => {
} }
// create the update doc // create the update doc
let updateDoc = {}; const updateDoc = {};
updateDoc.isAdmin = isAdmin; updateDoc.isAdmin = isAdmin;
updateDoc.usersName = req.body.usersName; updateDoc.usersName = req.body.usersName;
if(req.body.userPassword){ if(req.body.userPassword){
@ -145,7 +144,7 @@ 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
let urlParts = url.parse(req.header('Referer')); const urlParts = new URL(req.header('Referer'));
// Check number of users // Check number of users
db.users.count({}, (err, userCount) => { db.users.count({}, (err, userCount) => {
@ -156,7 +155,7 @@ router.post('/admin/user/insert', restrict, (req, res) => {
isAdmin = true; isAdmin = true;
} }
let doc = { const doc = {
usersName: req.body.usersName, usersName: req.body.usersName,
userEmail: req.body.userEmail, userEmail: req.body.userEmail,
userPassword: bcrypt.hashSync(req.body.userPassword, 10), userPassword: bcrypt.hashSync(req.body.userPassword, 10),
@ -164,7 +163,7 @@ router.post('/admin/user/insert', 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));