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

6
app.js
View File

@ -72,7 +72,7 @@ app.engine('hbs', handlebars({
extname: 'hbs',
layoutsDir: path.join(__dirname, 'views', 'layouts'),
defaultLayout: 'layout.hbs',
partialsDir: [ path.join(__dirname, 'views') ]
partialsDir: [path.join(__dirname, 'views')]
}));
app.set('view engine', 'hbs');
@ -224,7 +224,7 @@ handlebars = handlebars.create({
});
// session store
let store = new MongoStore({
const store = new MongoStore({
uri: config.databaseConnectionString,
collection: 'sessions'
});
@ -286,7 +286,7 @@ app.use('/authorizenet', authorizenet);
// catch 404 and forward to error handler
app.use((req, res, next) => {
let err = new Error('Not Found');
const err = new Error('Not Found');
err.status = 404;
next(err);
});

View File

@ -18,7 +18,7 @@ gulp.task('compressCss', () => {
return gulp.src(['public/stylesheets/*.css',
'!public/stylesheets/*.min.css'
])
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(cleanCSS({ compatibility: 'ie8' }))
.pipe(rename({
dirname: 'public/stylesheets',
extname: '.min.css'
@ -30,7 +30,7 @@ gulp.task('compressThemeCss', () => {
return gulp.src(['views/themes/**/*.css',
'!views/themes/**/*.min.css'
])
.pipe(cleanCSS({compatibility: 'ie8'}))
.pipe(cleanCSS({ compatibility: 'ie8' }))
.pipe(rename({
extname: '.min.css'
}))

View File

@ -67,7 +67,7 @@ const checkLogin = async (req, res, next) => {
// Middleware to check for admin access for certain route
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(req.session.isAdmin === false && routeCheck){

View File

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

View File

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

View File

@ -8,7 +8,7 @@ const testData = fs.readFileSync(path.join(__dirname, '..', 'bin', 'testdata.jso
const jsonData = JSON.parse(testData);
// get config
let config = getConfig();
const config = getConfig();
initDb(config.databaseConnectionString, (err, db) => {
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
router.get('/admin/login', (req, res) => {
let db = req.app.db;
const db = req.app.db;
db.users.count({}, (err, userCount) => {
if(err){
@ -58,7 +58,7 @@ router.get('/admin/login', (req, res) => {
// login the user and check the password
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) => {
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
router.get('/admin/setup', (req, res) => {
let db = req.app.db;
const db = req.app.db;
db.users.count({}, (err, userCount) => {
if(err){
@ -119,7 +119,7 @@ router.get('/admin/setup', (req, res) => {
router.post('/admin/setup_action', (req, res) => {
const db = req.app.db;
let doc = {
const doc = {
usersName: req.body.usersName,
userEmail: req.body.userEmail,
userPassword: bcrypt.hashSync(req.body.userPassword, 10),
@ -171,7 +171,7 @@ router.get('/admin/settings', restrict, (req, res) => {
// settings update
router.post('/admin/createApiKey', restrict, checkAccess, async (req, res) => {
const db = req.app.db;
let result = await db.users.findOneAndUpdate({
const result = await db.users.findOneAndUpdate({
_id: ObjectId(req.session.userId),
isAdmin: true
}, {
@ -208,7 +208,7 @@ router.post('/admin/settings/option/remove', restrict, checkAccess, (req, res) =
console.info(err.stack);
}
if(product && product.productOptions){
let optJson = JSON.parse(product.productOptions);
const 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) => {
@ -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) => {
const db = req.app.db;
let doc = {
const doc = {
pageName: req.body.pageName,
pageSlug: req.body.pageSlug,
pageEnabled: req.body.pageEnabled,
@ -375,7 +375,7 @@ router.get('/admin/settings/pages/delete/:page', restrict, checkAccess, (req, re
// new menu item
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){
req.session.message = 'Failed creating menu.';
req.session.messageType = 'danger';
@ -385,7 +385,7 @@ router.post('/admin/settings/menu/new', restrict, checkAccess, (req, res) => {
// update existing menu item
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){
req.session.message = 'Failed updating menu.';
req.session.messageType = 'danger';
@ -395,7 +395,7 @@ router.post('/admin/settings/menu/update', restrict, checkAccess, (req, res) =>
// delete menu item
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){
req.session.message = 'Failed deleting menu.';
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
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){
res.status(400).json({ message: 'Failed saving menu order' });
return;
@ -439,12 +439,12 @@ router.post('/admin/api/validate_permalink', (req, res) => {
});
// 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) => {
const db = req.app.db;
if(req.file){
let file = req.file;
const file = req.file;
// Get the mime type of the file
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;
let uploadDir = path.join('public/uploads', productPath);
const uploadDir = path.join('public/uploads', productPath);
// Check directory and create (if needed)
common.checkDirectorySync(uploadDir);
let source = fs.createReadStream(file.path);
let dest = fs.createWriteStream(path.join(uploadDir, file.originalname.replace(/ /g, '_')));
const source = fs.createReadStream(file.path);
const dest = fs.createWriteStream(path.join(uploadDir, file.originalname.replace(/ /g, '_')));
// save the new file
source.pipe(dest);
@ -491,7 +491,7 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
// delete the temp file.
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(!product.productImage){
@ -519,7 +519,7 @@ router.post('/admin/file/upload', restrict, checkAccess, upload.single('upload_f
// delete a file via ajax request
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
common.sendEmail(config.emailAddress, 'expressCart test email', 'Your email settings are working');
res.status(200).json({ message: 'Test email sent' });
@ -549,15 +549,15 @@ router.get('/admin/files', restrict, (req, res) => {
files.sort();
// declare the array of objects
let fileList = [];
let dirList = [];
const fileList = [];
const dirList = [];
// loop these files
for(let i = 0; i < files.length; i++){
// only want files
if(fs.lstatSync(files[i]).isDirectory() === false){
// declare the file object and set its values
let file = {
const file = {
id: i,
path: files[i].substring(6)
};
@ -565,7 +565,7 @@ router.get('/admin/files', restrict, (req, res) => {
// push the file object into the array
fileList.push(file);
}else{
let dir = {
const dir = {
id: i,
path: files[i].substring(6)
};

View File

@ -10,7 +10,7 @@ const { restrict } = require('../lib/auth');
router.post('/customer/create', (req, res) => {
const db = req.app.db;
let doc = {
const doc = {
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
@ -113,10 +113,10 @@ router.get('/admin/customers', restrict, (req, res) => {
// Filtered customers list
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;
const searchTerm = req.params.search;
const customersIndex = req.app.customersIndex;
let lunrIdArray = [];
const lunrIdArray = [];
customersIndex.search(searchTerm).forEach((id) => {
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
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
if(err){
@ -209,16 +209,16 @@ router.get('/customer/forgotten', (req, res) => {
router.post('/customer/forgotten_action', (req, res) => {
const db = req.app.db;
const config = req.app.config;
let passwordToken = randtoken.generate(30);
const passwordToken = randtoken.generate(30);
// find the user
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;
const tokenExpiry = Date.now() + 3600000;
db.customers.update({ email: req.body.email }, { $set: { resetToken: passwordToken, resetTokenExpiry: tokenExpiry } }, { multi: false }, (err, numReplaced) => {
// send forgotten password email
let mailOpts = {
const mailOpts = {
to: req.body.email,
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
@ -281,9 +281,9 @@ router.post('/customer/reset/:token', (req, res) => {
}
// 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) => {
let mailOpts = {
const mailOpts = {
to: customer.email,
subject: 'Password successfully reset',
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
router.get('/payment/:orderId', async (req, res, next) => {
let db = req.app.db;
let config = req.app.config;
const db = req.app.db;
const config = req.app.config;
// render the payment complete message
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) => {
let config = req.app.config;
const config = req.app.config;
// if there is no items in the cart then render a failure
if(!req.session.cart){
@ -136,8 +136,8 @@ router.get('/cartPartial', (req, res) => {
// show an individual product
router.get('/product/:id', (req, res) => {
let db = req.app.db;
let config = req.app.config;
const db = req.app.db;
const config = req.app.config;
db.products.findOne({ $or: [{ _id: getId(req.params.id) }, { productPermalink: req.params.id }] }, (err, result) => {
// render 404 if page is not published
@ -147,7 +147,7 @@ router.get('/product/:id', (req, res) => {
if(err || result == null || result.productPublished === 'false'){
res.render('error', { title: 'Not found', message: 'Product not found', helpers: req.handlebars.helpers, config });
}else{
let productOptions = result.productOptions;
const productOptions = result.productOptions;
// If JSON query param return json instead
if(req.query.json === 'true'){
@ -183,12 +183,12 @@ router.get('/product/:id', (req, res) => {
router.post('/product/updatecart', (req, res, next) => {
const db = req.app.db;
const config = req.app.config;
let cartItems = JSON.parse(req.body.items);
const cartItems = JSON.parse(req.body.items);
let hasError = false;
let stockError = false;
async.eachSeries(cartItems, (cartItem, callback) => {
let productQuantity = cartItem.itemQuantity ? cartItem.itemQuantity : 1;
const productQuantity = cartItem.itemQuantity ? cartItem.itemQuantity : 1;
if(cartItem.itemQuantity === 0){
// quantity equals zero so we remove the item
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]){
req.session.cart[cartItem.cartIndex].quantity = 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.
let options = {};
if(req.body.productOptions){
options = JSON.parse(req.body.productOptions);
}
let findDoc = {
const findDoc = {
productId: req.body.productId,
options: options
};
// 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;
if(cartIndex > -1){
cartQuantity = parseInt(req.session.cart[cartIndex].quantity) + productQuantity;
@ -378,7 +378,7 @@ router.post('/product/addtocart', (req, res, next) => {
cartQuantity = productQuantity;
// new product deets
let productObj = {};
const productObj = {};
productObj.productId = req.body.productId;
productObj.title = product.productTitle;
productObj.quantity = productQuantity;
@ -412,13 +412,13 @@ router.post('/product/addtocart', (req, res, next) => {
// search products
router.get('/search/:searchTerm/:pageNum?', (req, res) => {
let db = req.app.db;
let searchTerm = req.params.searchTerm;
let productsIndex = req.app.productsIndex;
let config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
const db = req.app.db;
const searchTerm = req.params.searchTerm;
const productsIndex = req.app.productsIndex;
const config = req.app.config;
const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let lunrIdArray = [];
const lunrIdArray = [];
productsIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(getId(id.ref));
});
@ -466,13 +466,13 @@ router.get('/search/:searchTerm/:pageNum?', (req, res) => {
// search products
router.get('/category/:cat/:pageNum?', (req, res) => {
let db = req.app.db;
let searchTerm = req.params.cat;
let productsIndex = req.app.productsIndex;
let config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
const db = req.app.db;
const searchTerm = req.params.cat;
const productsIndex = req.app.productsIndex;
const config = req.app.config;
const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let lunrIdArray = [];
const lunrIdArray = [];
productsIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(getId(id.ref));
});
@ -523,14 +523,14 @@ router.get('/category/:cat/:pageNum?', (req, res) => {
// return sitemap
router.get('/sitemap.xml', (req, res, next) => {
let sm = require('sitemap');
let config = req.app.config;
const sm = require('sitemap');
const config = req.app.config;
addSitemapProducts(req, res, (err, products) => {
if(err){
console.error(colors.red('Error generating sitemap.xml', err));
}
let sitemap = sm.createSitemap(
const sitemap = sm.createSitemap(
{
hostname: config.baseUrl,
cacheTime: 600000,
@ -539,8 +539,8 @@ router.get('/sitemap.xml', (req, res, next) => {
]
});
let currentUrls = sitemap.urls;
let mergedUrls = currentUrls.concat(products);
const currentUrls = sitemap.urls;
const mergedUrls = currentUrls.concat(products);
sitemap.urls = mergedUrls;
// render the sitemap
sitemap.toXML((err, xml) => {
@ -555,9 +555,9 @@ router.get('/sitemap.xml', (req, res, next) => {
});
router.get('/page/:pageNum', (req, res, next) => {
let db = req.app.db;
let config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
const db = req.app.db;
const config = req.app.config;
const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
Promise.all([
getData(req, req.params.pageNum),
@ -595,9 +595,9 @@ router.get('/page/:pageNum', (req, res, next) => {
// The main entry point of the shop
router.get('/:page?', (req, res, next) => {
let db = req.app.db;
let config = req.app.config;
let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
const db = req.app.db;
const config = req.app.config;
const numberProducts = config.productsPerPage ? config.productsPerPage : 6;
// if no page is specified, just render page 1 of the cart
if(!req.params.page){

View File

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

View File

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

View File

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

View File

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

View File

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