expressCart/lib/common.js

730 lines
21 KiB
JavaScript
Raw Normal View History

2018-01-07 06:07:10 +10:00
const _ = require('lodash');
const uglifycss = require('uglifycss');
const colors = require('colors');
const lunr = require('lunr');
2018-01-15 07:11:22 +10:00
const cheerio = require('cheerio');
2018-01-07 23:10:16 +10:00
const fs = require('fs');
2018-01-15 07:11:22 +10:00
const path = require('path');
const glob = require('glob');
const async = require('async');
const nodemailer = require('nodemailer');
2018-12-11 23:31:56 +10:00
const sanitizeHtml = require('sanitize-html');
2018-01-07 06:07:10 +10:00
const escape = require('html-entities').AllHtmlEntities;
const mkdirp = require('mkdirp');
let ObjectId = require('mongodb').ObjectID;
2018-01-07 04:55:48 +10:00
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'}
];
2018-06-01 21:31:23 +10:00
// Allowed mime types for product images
exports.allowedMimeType = [
'image/jpeg',
'image/png',
'image/gif',
'image/bmp',
'image/webp'
];
exports.fileSizeLimit = 10485760;
2018-01-07 04:55:48 +10:00
// common functions
exports.restrict = (req, res, next) => {
exports.checkLogin(req, res, next);
};
2018-01-15 07:11:22 +10:00
exports.checkLogin = (req, res, next) => {
2018-01-07 04:55:48 +10:00
// if not protecting we check for public pages and don't checkLogin
if(req.session.needsSetup === true){
2018-02-04 01:23:59 +10:00
res.redirect('/admin/setup');
2018-01-07 04:55:48 +10:00
return;
}
if(req.session.user){
next();
return;
}
2018-02-04 01:23:59 +10:00
res.redirect('/admin/login');
2018-01-07 04:55:48 +10:00
};
2018-12-11 23:31:56 +10:00
exports.cleanHtml = (html) => {
return sanitizeHtml(html);
};
2018-08-31 13:30:27 +10:00
exports.mongoSanitize = (param) => {
if(param instanceof Object){
for(const key in param){
if(/^\$/.test(key)){
2018-08-31 13:30:27 +10:00
delete param[key];
}
}
}
return param;
};
exports.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();
}
};
2018-01-15 07:11:22 +10:00
exports.showCartCloseBtn = (page) => {
2018-01-07 04:55:48 +10:00
let showCartCloseButton = true;
if(page === 'checkout' || page === 'pay'){
showCartCloseButton = false;
}
return showCartCloseButton;
};
// adds products to sitemap.xml
2018-01-15 07:11:22 +10:00
exports.addSitemapProducts = (req, res, cb) => {
2018-01-07 04:55:48 +10:00
let db = req.app.db;
2018-01-15 07:11:22 +10:00
2018-01-07 05:35:49 +10:00
let config = exports.getConfig();
2018-01-07 04:55:48 +10:00
let hostname = config.baseUrl;
db.products.find({productPublished: 'true'}).toArray((err, products) => {
2018-01-07 04:55:48 +10:00
let posts = [];
if(err){
cb(null, posts);
}
async.eachSeries(products, (item, callback) => {
let post = {};
let url = item._id;
if(item.productPermalink){
url = item.productPermalink;
}
post.url = hostname + '/' + url;
post.changefreq = 'weekly';
post.priority = 0.7;
posts.push(post);
callback(null, posts);
}, () => {
cb(null, posts);
});
});
};
2018-01-15 07:11:22 +10:00
exports.clearSessionValue = (session, sessionVar) => {
2018-01-07 04:55:48 +10:00
let temp;
if(session){
temp = session[sessionVar];
session[sessionVar] = null;
}
return temp;
};
2018-01-15 07:11:22 +10:00
exports.updateTotalCartAmount = (req, res) => {
2018-01-07 05:35:49 +10:00
let config = exports.getConfig();
2018-01-07 04:55:48 +10:00
req.session.totalCartAmount = 0;
_(req.session.cart).forEach((item) => {
req.session.totalCartAmount = req.session.totalCartAmount + item.totalItemPrice;
});
// under the free shipping threshold
if(req.session.totalCartAmount < config.freeShippingAmount){
req.session.totalCartAmount = req.session.totalCartAmount + parseInt(config.flatShipping);
req.session.shippingCostApplied = true;
}else{
req.session.shippingCostApplied = false;
}
};
2018-01-15 07:11:22 +10:00
exports.checkDirectorySync = (directory) => {
2018-01-07 04:55:48 +10:00
try{
fs.statSync(directory);
}catch(e){
try{
2018-01-07 04:55:48 +10:00
fs.mkdirSync(directory);
}
catch(err){
mkdirp.sync(directory);//error : directory & sub directories to be newly created
}
2018-01-07 04:55:48 +10:00
}
};
2018-01-15 07:11:22 +10:00
exports.getThemes = () => {
2018-02-12 05:47:26 +10:00
return fs.readdirSync(path.join(__dirname, '../', 'views', 'themes')).filter(file => fs.statSync(path.join(path.join(__dirname, '../', 'views', 'themes'), file)).isDirectory());
2018-01-07 04:55:48 +10:00
};
2018-01-15 07:11:22 +10:00
exports.getImages = (dir, req, res, callback) => {
2018-01-07 04:55:48 +10:00
let db = req.app.db;
db.products.findOne({_id: exports.getId(dir)}, (err, product) => {
if(err){
console.error(colors.red('Error getting images', err));
}
2018-01-07 23:10:16 +10:00
2018-01-07 04:55:48 +10:00
// loop files in /public/uploads/
2018-01-07 23:10:16 +10:00
glob('public/uploads/' + product.productPermalink + '/**', {nosort: true}, (er, files) => {
2018-01-07 04:55:48 +10:00
// sort array
files.sort();
// declare the array of objects
let 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 = {
id: i,
path: files[i].substring(6)
};
if(product.productImage === files[i].substring(6)){
file.productImage = true;
}
// push the file object into the array
fileList.push(file);
}
}
callback(fileList);
});
});
};
exports.getConfigFilename = () => {
let filename = path.join(__dirname, '../config', 'settings-local.json');
2018-10-05 21:58:33 +10:00
if(fs.existsSync(filename)){
return filename;
}
2018-10-05 21:58:33 +10:00
return path.join(__dirname, '../config', 'settings.json');
};
2018-01-15 07:11:22 +10:00
exports.getConfig = () => {
let config = JSON.parse(fs.readFileSync(exports.getConfigFilename(), 'utf8'));
2018-01-07 04:55:48 +10:00
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;
// set the environment for files
config.env = '.min';
if(process.env.NODE_ENV === 'development' || process.env.NODE_ENV === undefined){
config.env = '';
}
// setup theme
config.themeViews = '';
if(typeof config.theme === 'undefined' || config.theme === ''){
config.theme = 'Cloth'; // Default to Cloth theme
2018-01-07 04:55:48 +10:00
}
2018-02-12 05:47:26 +10:00
config.themeViews = '../views/themes/' + config.theme + '/';
2018-01-07 04:55:48 +10:00
// if db set to mongodb override connection with MONGODB_CONNECTION_STRING env var
2018-01-07 05:35:49 +10:00
config.databaseConnectionString = process.env.MONGODB_CONNECTION_STRING || config.databaseConnectionString;
2018-01-07 04:55:48 +10:00
return config;
};
2018-01-15 07:11:22 +10:00
exports.getPaymentConfig = () => {
2018-01-07 04:55:48 +10:00
let siteConfig = this.getConfig();
let config = [];
if(fs.existsSync(path.join(__dirname, '../config/' + siteConfig.paymentGateway + '.json'))){
config = JSON.parse(fs.readFileSync(path.join(__dirname, '../config/' + siteConfig.paymentGateway + '.json'), 'utf8'));
}
return config;
};
2018-01-15 07:11:22 +10:00
exports.updateConfig = (fields) => {
let settingsFile = exports.getConfig();
2018-01-07 04:55:48 +10:00
_.forEach(fields, (value, key) => {
settingsFile[key] = value;
if(key === 'customCss_input'){
settingsFile['customCss'] = escape.encode(uglifycss.processString(value));
}
if(key === 'footerHtml_input'){
let footerHtml = typeof value !== 'undefined' || value === '' ? escape.encode(value) : '';
settingsFile['footerHtml'] = footerHtml;
}
if(key === 'googleAnalytics_input'){
let googleAnalytics = typeof value !== 'undefined' ? escape.encode(value) : '';
settingsFile['googleAnalytics'] = googleAnalytics;
}
});
// delete settings
delete settingsFile['customCss_input'];
delete settingsFile['footerHtml_input'];
delete settingsFile['googleAnalytics_input'];
if(fields['emailSecure'] === 'on'){
settingsFile['emailSecure'] = true;
}else{
settingsFile['emailSecure'] = false;
}
if(!fields['menuEnabled']){
settingsFile['menuEnabled'] = false;
2018-01-07 04:55:48 +10:00
}else{
settingsFile['menuEnabled'] = true;
}
if(fields['emailPort']){
settingsFile['emailPort'] = parseInt(fields['emailPort']);
}
if(fields['flatShipping']){
settingsFile['flatShipping'] = parseInt(fields['flatShipping']);
}
if(fields['freeShippingAmount']){
settingsFile['freeShippingAmount'] = parseInt(fields['freeShippingAmount']);
}
if(fields['productsPerRow']){
settingsFile['productsPerRow'] = parseInt(fields['productsPerRow']);
}
if(fields['productsPerPage']){
settingsFile['productsPerPage'] = parseInt(fields['productsPerPage']);
2018-01-07 04:55:48 +10:00
}
// write file
try{
fs.writeFileSync(exports.getConfigFilename(), JSON.stringify(settingsFile, null, 4));
2018-01-07 04:55:48 +10:00
return true;
}catch(exception){
return false;
}
};
2018-01-15 07:11:22 +10:00
exports.getMenu = (db) => {
return db.menu.findOne({});
2018-01-07 04:55:48 +10:00
};
// creates a new menu item
2018-01-15 07:11:22 +10:00
exports.newMenu = (req, res) => {
const db = req.app.db;
return exports.getMenu(db)
.then((menu) => {
// if no menu present
if(!menu){
menu = {};
menu.items = [];
}
let newNav = {
title: req.body.navMenu,
link: req.body.navLink,
order: Object.keys(menu.items).length + 1
};
menu.items.push(newNav);
return db.menu.updateOne({}, {$set: {items: menu.items}}, {upsert: true})
.then(() => {
return true;
});
})
.catch((err) => {
console.log('Error creating new menu', err);
2018-01-07 04:55:48 +10:00
return false;
});
2018-01-07 04:55:48 +10:00
};
// delete a menu item
2018-01-15 07:11:22 +10:00
exports.deleteMenu = (req, res, menuIndex) => {
const db = req.app.db;
return exports.getMenu(db)
.then((menu) => {
// Remove menu item
menu.items.splice(menuIndex, 1);
return db.menu.updateOne({}, {$set: {items: menu.items}}, {upsert: true})
.then(() => {
return true;
});
})
.catch(() => {
2018-01-07 04:55:48 +10:00
return false;
});
2018-01-07 04:55:48 +10:00
};
// updates and existing menu item
2018-01-15 07:11:22 +10:00
exports.updateMenu = (req, res) => {
const db = req.app.db;
return exports.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})
.then(() => {
return true;
});
})
.catch(() => {
return false;
});
};
2018-01-07 04:55:48 +10:00
2018-01-15 07:11:22 +10:00
exports.sortMenu = (menu) => {
if(menu && menu.items){
menu.items = _.sortBy(menu.items, 'order');
return menu;
}
return{};
};
2018-01-07 04:55:48 +10:00
// orders the menu
2018-01-15 07:11:22 +10:00
exports.orderMenu = (req, res) => {
const db = req.app.db;
return exports.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})
.then(() => {
return true;
});
})
.catch(() => {
2018-01-07 04:55:48 +10:00
return false;
});
2018-01-07 04:55:48 +10:00
};
2018-01-15 07:11:22 +10:00
exports.getEmailTemplate = (result) => {
2018-01-07 04:55:48 +10:00
let config = this.getConfig();
let template = fs.readFileSync(path.join(__dirname, '../public/email_template.html'), 'utf8');
$ = cheerio.load(template);
$('#brand').text(config.cartTitle);
$('#paymentResult').text(result.message);
if(result.paymentApproved === true){
$('#paymentResult').addClass('text-success');
}else{
$('#paymentResult').addClass('text-danger');
}
$('#paymentMessage').text('Thanks for shopping with us. We hope you will shop with us again soon.');
$('#paymentDetails').html(result.paymentDetails);
return $.html();
};
2018-01-15 07:11:22 +10:00
exports.sendEmail = (to, subject, body) => {
2018-01-07 04:55:48 +10:00
let config = this.getConfig();
let emailSettings = {
host: config.emailHost,
port: config.emailPort,
secure: config.emailSecure,
auth: {
user: config.emailUser,
pass: config.emailPassword
}
};
// outlook needs this setting
if(config.emailHost === 'smtp-mail.outlook.com'){
emailSettings.tls = {ciphers: 'SSLv3'};
}
let transporter = nodemailer.createTransport(emailSettings);
let mailOptions = {
from: config.emailAddress, // sender address
to: to, // list of receivers
subject: subject, // Subject line
html: body// html body
};
transporter.sendMail(mailOptions, (error, info) => {
if(error){
return console.error(colors.red(error));
}
return true;
});
};
// gets the correct type of index ID
2018-01-15 07:11:22 +10:00
exports.getId = (id) => {
2018-01-07 04:55:48 +10:00
if(id){
if(id.length !== 24){
return id;
}
}
return ObjectId(id);
2018-01-07 04:55:48 +10:00
};
exports.getData = (req, page, query) => {
2018-01-15 07:11:22 +10:00
let db = req.app.db;
let config = exports.getConfig();
let numberProducts = config.productsPerPage ? config.productsPerPage : 6;
let skip = 0;
if(page > 1){
skip = (page - 1) * numberProducts;
}
2018-02-12 05:47:26 +10:00
if(!query){
query = {};
}
2018-01-15 07:11:22 +10:00
query['productPublished'] = 'true';
// Run our queries
return Promise.all([
db.products.find(query).skip(skip).limit(parseInt(numberProducts)).toArray(),
db.products.count(query)
])
.then((result) => {
const returnData = {data: result[0], totalProducts: result[1]};
return returnData;
})
.catch((err) => {
throw new Error('Error retrieving products');
});
};
2018-01-07 06:07:10 +10:00
exports.indexProducts = (app) => {
// index all products in lunr on startup
return new Promise((resolve, reject) => {
app.db.products.find({}).toArray((err, productsList) => {
2018-01-07 06:07:10 +10:00
if(err){
console.error(colors.red(err.stack));
reject(err);
}
// setup lunr indexing
2018-01-15 07:11:22 +10:00
const productsIndex = lunr(function(){
2018-01-07 06:07:10 +10:00
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();
});
});
};
2018-01-07 06:07:10 +10:00
exports.indexOrders = (app, cb) => {
// index all orders in lunr on startup
return new Promise((resolve, reject) => {
app.db.orders.find({}).toArray((err, ordersList) => {
2018-01-07 06:07:10 +10:00
if(err){
console.error(colors.red('Error setting up products index: ' + err));
reject(err);
}
// setup lunr indexing
2018-01-15 07:11:22 +10:00
const ordersIndex = lunr(function(){
2018-01-07 06:07:10 +10:00
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();
});
});
};
// 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)
2018-01-07 06:07:10 +10:00
])
.catch((err) => {
process.exit(2);
});
};
2018-01-07 23:10:16 +10:00
2018-02-23 03:41:24 +10:00
exports.dropTestData = (db) => {
Promise.all([
db.products.drop(),
db.users.drop(),
db.customers.drop()
])
.then((err) => {
return Promise.resolve();
})
.catch((err) => {
console.log('Error dropping test data', err);
});
};
exports.sampleData = (app) => {
const db = app.db;
db.products.count()
2018-01-07 23:10:16 +10:00
.then((products) => {
2018-02-23 03:41:24 +10:00
if(products !== 0){
2018-01-07 23:10:16 +10:00
return Promise.resolve();
}
2018-02-23 03:41:24 +10:00
console.log('Inserting sample data');
const testData = fs.readFileSync('./bin/testdata.json', 'utf-8');
const jsonData = JSON.parse(testData);
2018-02-23 03:41:24 +10:00
// Add sample data
2018-01-07 23:10:16 +10:00
return Promise.all([
2018-02-23 05:10:15 +10:00
db.products.insertMany(fixProductDates(jsonData.products)),
2018-02-23 03:41:24 +10:00
db.menu.insertOne(jsonData.menu)
]);
});
};
exports.testData = async (app) => {
const db = app.db;
const testData = fs.readFileSync('./bin/testdata.json', 'utf-8');
const jsonData = JSON.parse(testData);
// TODO: A bit ugly, needs fixing
return new Promise((resolve, reject) => {
Promise.all([
db.users.remove({}, {}),
db.customers.remove({}, {}),
2018-02-23 05:10:15 +10:00
db.products.remove({}, {}),
db.menu.remove({}, {})
2018-01-07 23:10:16 +10:00
])
2018-02-23 03:41:24 +10:00
.then(() => {
Promise.all([
db.users.insertMany(jsonData.users),
db.customers.insertMany(jsonData.customers),
2018-02-23 05:10:15 +10:00
db.products.insertMany(fixProductDates(jsonData.products)),
2018-02-23 03:41:24 +10:00
db.menu.insertOne(jsonData.menu)
])
.then(() => {
resolve();
})
.catch((err) => {
2018-02-23 05:10:15 +10:00
console.log('Error inserting test data', err);
2018-02-23 03:41:24 +10:00
reject(err);
});
})
2018-01-07 23:10:16 +10:00
.catch((err) => {
2018-02-23 05:10:15 +10:00
console.log('Error removing existing test data', err);
2018-02-23 03:41:24 +10:00
reject(err);
2018-01-07 23:10:16 +10:00
});
});
};
2018-02-23 05:10:15 +10:00
// Adds current date to product added date when smashing into DB
function fixProductDates(products){
let index = 0;
products.forEach((product) => {
products[index].productAddedDate = new Date();
index++;
});
return products;
}