expressCart/routes/customer.js

620 lines
21 KiB
JavaScript
Raw Normal View History

2018-02-03 23:26:09 +10:00
const express = require('express');
const router = express.Router();
const colors = require('colors');
const randtoken = require('rand-token');
2018-02-04 22:04:32 +10:00
const bcrypt = require('bcryptjs');
const {
getId,
clearSessionValue,
getCountryList,
mongoSanitize,
sendEmail,
clearCustomer
} = require('../lib/common');
const rateLimit = require('express-rate-limit');
2019-11-16 21:05:02 +10:00
const { indexCustomers } = require('../lib/indexing');
2019-11-16 09:02:15 +10:00
const { validateJson } = require('../lib/schema');
2019-06-15 14:46:08 +10:00
const { restrict } = require('../lib/auth');
2018-02-03 23:26:09 +10:00
const apiLimiter = rateLimit({
windowMs: 300000, // 5 minutes
max: 5
});
2018-02-03 23:26:09 +10:00
// insert a customer
2019-11-09 14:21:48 +10:00
router.post('/customer/create', async (req, res) => {
2018-02-03 23:26:09 +10:00
const db = req.app.db;
2019-11-16 09:02:15 +10:00
const customerObj = {
2018-02-03 23:26:09 +10:00
email: req.body.email,
company: req.body.company,
2018-02-03 23:26:09 +10:00
firstName: req.body.firstName,
lastName: req.body.lastName,
address1: req.body.address1,
address2: req.body.address2,
country: req.body.country,
state: req.body.state,
postcode: req.body.postcode,
phone: req.body.phone,
2018-02-04 22:04:32 +10:00
password: bcrypt.hashSync(req.body.password, 10),
2018-02-03 23:26:09 +10:00
created: new Date()
};
2019-11-16 20:57:48 +10:00
const schemaResult = validateJson('newCustomer', customerObj);
if(!schemaResult.result){
2019-11-16 09:02:15 +10:00
res.status(400).json(schemaResult.errors);
return;
}
2018-02-03 23:26:09 +10:00
// check for existing customer
2019-11-09 14:21:48 +10:00
const customer = await db.customers.findOne({ email: req.body.email });
if(customer){
res.status(400).json({
2019-11-23 08:35:19 +10:00
message: 'A customer already exists with that email address'
2019-11-09 14:21:48 +10:00
});
return;
}
2019-11-16 09:02:15 +10:00
// email is ok to be used.
2019-11-09 14:21:48 +10:00
try{
2019-11-16 09:02:15 +10:00
const newCustomer = await db.customers.insertOne(customerObj);
2019-11-16 21:05:02 +10:00
indexCustomers(req.app)
.then(() => {
// Return the new customer
2019-11-16 21:05:02 +10:00
const customerReturn = newCustomer.ops[0];
delete customerReturn.password;
// Set the customer into the session
req.session.customerPresent = true;
req.session.customerId = customerReturn._id;
req.session.customerEmail = customerReturn.email;
req.session.customerCompany = customerReturn.company;
req.session.customerFirstname = customerReturn.firstName;
req.session.customerLastname = customerReturn.lastName;
req.session.customerAddress1 = customerReturn.address1;
req.session.customerAddress2 = customerReturn.address2;
req.session.customerCountry = customerReturn.country;
req.session.customerState = customerReturn.state;
req.session.customerPostcode = customerReturn.postcode;
req.session.customerPhone = customerReturn.phone;
req.session.orderComment = req.body.orderComment;
// Return customer oject
2019-11-16 21:05:02 +10:00
res.status(200).json(customerReturn);
});
2019-11-09 14:21:48 +10:00
}catch(ex){
console.error(colors.red('Failed to insert customer: ', ex));
res.status(400).json({
2019-11-23 08:35:19 +10:00
message: 'Customer creation failed.'
2019-11-09 14:21:48 +10:00
});
}
2018-02-03 23:26:09 +10:00
});
router.post('/customer/save', async (req, res) => {
const customerObj = {
email: req.body.email,
company: req.body.company,
firstName: req.body.firstName,
lastName: req.body.lastName,
address1: req.body.address1,
address2: req.body.address2,
country: req.body.country,
state: req.body.state,
postcode: req.body.postcode,
phone: req.body.phone
};
const schemaResult = validateJson('saveCustomer', customerObj);
if(!schemaResult.result){
res.status(400).json(schemaResult.errors);
return;
}
// Set the customer into the session
req.session.customerPresent = true;
req.session.customerEmail = customerObj.email;
req.session.customerCompany = customerObj.company;
req.session.customerFirstname = customerObj.firstName;
req.session.customerLastname = customerObj.lastName;
req.session.customerAddress1 = customerObj.address1;
req.session.customerAddress2 = customerObj.address2;
req.session.customerCountry = customerObj.country;
req.session.customerState = customerObj.state;
req.session.customerPostcode = customerObj.postcode;
req.session.customerPhone = customerObj.phone;
req.session.orderComment = req.body.orderComment;
res.status(200).json(customerObj);
});
// Get customer orders
router.get('/customer/account', async (req, res) => {
const db = req.app.db;
const config = req.app.config;
if(!req.session.customerPresent){
res.redirect('/customer/login');
return;
}
const orders = await db.orders.find({
orderCustomer: getId(req.session.customerId)
})
.sort({ orderDate: -1 })
.toArray();
res.render(`${config.themeViews}customer-account`, {
title: 'Orders',
session: req.session,
orders,
message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'),
countryList: getCountryList(),
config: req.app.config,
helpers: req.handlebars.helpers
});
});
// Update a customer
router.post('/customer/update', async (req, res) => {
const db = req.app.db;
if(!req.session.customerPresent){
res.redirect('/customer/login');
return;
}
const customerObj = {
company: req.body.company,
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
address1: req.body.address1,
address2: req.body.address2,
country: req.body.country,
state: req.body.state,
postcode: req.body.postcode,
phone: req.body.phone
};
const schemaResult = validateJson('editCustomer', customerObj);
if(!schemaResult.result){
console.log('errors', schemaResult.errors);
res.status(400).json(schemaResult.errors);
return;
}
// check for existing customer
const customer = await db.customers.findOne({ _id: getId(req.session.customerId) });
if(!customer){
res.status(400).json({
message: 'Customer not found'
});
return;
}
// Update customer
try{
const updatedCustomer = await db.customers.findOneAndUpdate(
{ _id: getId(req.session.customerId) },
{
$set: customerObj
}, { multi: false, returnOriginal: false }
);
indexCustomers(req.app)
.then(() => {
// Set the customer into the session
req.session.customerEmail = customerObj.email;
req.session.customerCompany = customerObj.company;
req.session.customerFirstname = customerObj.firstName;
req.session.customerLastname = customerObj.lastName;
req.session.customerAddress1 = customerObj.address1;
req.session.customerAddress2 = customerObj.address2;
req.session.customerCountry = customerObj.country;
req.session.customerState = customerObj.state;
req.session.customerPostcode = customerObj.postcode;
req.session.customerPhone = customerObj.phone;
req.session.orderComment = req.body.orderComment;
res.status(200).json({ message: 'Customer updated', customer: updatedCustomer.value });
});
}catch(ex){
console.error(colors.red('Failed updating customer: ' + ex));
res.status(400).json({ message: 'Failed to update customer' });
}
});
2019-11-16 20:57:48 +10:00
// Update a customer
router.post('/admin/customer/update', restrict, async (req, res) => {
const db = req.app.db;
const customerObj = {
company: req.body.company,
2019-11-16 20:57:48 +10:00
email: req.body.email,
firstName: req.body.firstName,
lastName: req.body.lastName,
address1: req.body.address1,
address2: req.body.address2,
country: req.body.country,
state: req.body.state,
postcode: req.body.postcode,
phone: req.body.phone
};
// Handle optional values
if(req.body.password){ customerObj.password = bcrypt.hashSync(req.body.password, 10); }
const schemaResult = validateJson('editCustomer', customerObj);
if(!schemaResult.result){
console.log('errors', schemaResult.errors);
2019-12-07 14:00:45 +10:00
res.status(400).json(schemaResult.errors);
2019-11-16 20:57:48 +10:00
return;
}
// check for existing customer
const customer = await db.customers.findOne({ _id: getId(req.body.customerId) });
2019-11-16 20:57:48 +10:00
if(!customer){
2019-12-07 14:00:45 +10:00
res.status(400).json({
message: 'Customer not found'
});
2019-11-16 20:57:48 +10:00
return;
}
// Update customer
try{
const updatedCustomer = await db.customers.findOneAndUpdate(
{ _id: getId(req.body.customerId) },
2019-11-16 20:57:48 +10:00
{
$set: customerObj
}, { multi: false, returnOriginal: false }
);
2019-11-16 21:05:02 +10:00
indexCustomers(req.app)
.then(() => {
2019-12-07 14:00:45 +10:00
const returnCustomer = updatedCustomer.value;
delete returnCustomer.password;
res.status(200).json({ message: 'Customer updated', customer: updatedCustomer.value });
2019-11-16 21:05:02 +10:00
});
2019-11-16 20:57:48 +10:00
}catch(ex){
console.error(colors.red('Failed updating customer: ' + ex));
2019-12-07 14:00:45 +10:00
res.status(400).json({ message: 'Failed to update customer' });
2019-11-16 20:57:48 +10:00
}
});
2019-11-23 08:35:19 +10:00
// Delete a customer
router.delete('/admin/customer', restrict, async (req, res) => {
const db = req.app.db;
// check for existing customer
const customer = await db.customers.findOne({ _id: getId(req.body.customerId) });
2019-11-23 08:35:19 +10:00
if(!customer){
2019-12-07 14:00:45 +10:00
res.status(400).json({
message: 'Failed to delete customer. Customer not found'
});
2019-12-07 17:22:27 +10:00
return;
2019-11-23 08:35:19 +10:00
}
// Update customer
try{
await db.customers.deleteOne({ _id: getId(req.body.customerId) });
2019-11-23 08:35:19 +10:00
indexCustomers(req.app)
.then(() => {
res.status(200).json({ message: 'Customer deleted' });
});
}catch(ex){
console.error(colors.red('Failed deleting customer: ' + ex));
2019-12-07 14:00:45 +10:00
res.status(400).json({ message: 'Failed to delete customer' });
2019-11-23 08:35:19 +10:00
}
});
2018-02-05 23:20:44 +10:00
// render the customer view
2019-11-09 14:21:48 +10:00
router.get('/admin/customer/view/:id?', restrict, async (req, res) => {
2018-02-05 23:20:44 +10:00
const db = req.app.db;
const customer = await db.customers.findOne({ _id: getId(req.params.id) });
2018-02-05 23:20:44 +10:00
2019-11-09 14:21:48 +10:00
if(!customer){
// If API request, return json
if(req.apiAuthenticated){
2019-11-09 14:21:48 +10:00
return res.status(400).json({ message: 'Customer not found' });
}
2019-11-09 14:21:48 +10:00
req.session.message = 'Customer not found';
req.session.message_type = 'danger';
return res.redirect('/admin/customers');
}
// If API request, return json
if(req.apiAuthenticated){
return res.status(200).json(customer);
}
return res.render('customer', {
title: 'View customer',
result: customer,
admin: true,
session: req.session,
message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'),
countryList: getCountryList(),
2019-11-09 14:21:48 +10:00
config: req.app.config,
editor: true,
helpers: req.handlebars.helpers
2018-02-05 23:20:44 +10:00
});
});
// customers list
2019-11-09 14:21:48 +10:00
router.get('/admin/customers', restrict, async (req, res) => {
2018-02-05 23:20:44 +10:00
const db = req.app.db;
2019-11-09 14:21:48 +10:00
const customers = await db.customers.find({}).limit(20).sort({ created: -1 }).toArray();
2019-11-09 14:21:48 +10:00
// If API request, return json
if(req.apiAuthenticated){
return res.status(200).json(customers);
}
return res.render('customers', {
title: 'Customers - List',
admin: true,
customers: customers,
session: req.session,
helpers: req.handlebars.helpers,
message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'),
2019-11-09 14:21:48 +10:00
config: req.app.config
2018-02-05 23:20:44 +10:00
});
});
// Filtered customers list
2019-11-09 14:21:48 +10:00
router.get('/admin/customers/filter/:search', restrict, async (req, res, next) => {
2018-02-05 23:20:44 +10:00
const db = req.app.db;
2019-07-12 18:06:34 +10:00
const searchTerm = req.params.search;
const customersIndex = req.app.customersIndex;
2018-02-05 23:20:44 +10:00
2019-07-12 18:06:34 +10:00
const lunrIdArray = [];
2018-02-05 23:20:44 +10:00
customersIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(getId(id.ref));
2018-02-05 23:20:44 +10:00
});
// we search on the lunr indexes
2019-11-09 14:21:48 +10:00
const customers = await db.customers.find({ _id: { $in: lunrIdArray } }).sort({ created: -1 }).toArray();
2019-11-09 14:21:48 +10:00
// If API request, return json
if(req.apiAuthenticated){
return res.status(200).json({
customers
2018-02-05 23:20:44 +10:00
});
2019-11-09 14:21:48 +10:00
}
return res.render('customers', {
title: 'Customer results',
customers: customers,
admin: true,
config: req.app.config,
session: req.session,
searchTerm: searchTerm,
message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'),
2019-11-09 14:21:48 +10:00
helpers: req.handlebars.helpers
2018-02-05 23:20:44 +10:00
});
});
router.post('/admin/customer/lookup', restrict, async (req, res, next) => {
const db = req.app.db;
const customerEmail = req.body.customerEmail;
// Search for a customer
const customer = await db.customers.findOne({ email: customerEmail });
if(customer){
req.session.customerPresent = true;
req.session.customerId = customer._id;
req.session.customerEmail = customer.email;
req.session.customerCompany = customer.company;
req.session.customerFirstname = customer.firstName;
req.session.customerLastname = customer.lastName;
req.session.customerAddress1 = customer.address1;
req.session.customerAddress2 = customer.address2;
req.session.customerCountry = customer.country;
req.session.customerState = customer.state;
req.session.customerPostcode = customer.postcode;
req.session.customerPhone = customer.phone;
return res.status(200).json({
message: 'Customer found',
customer
});
}
return res.status(400).json({
message: 'No customers found'
});
});
router.get('/customer/login', async (req, res, next) => {
const config = req.app.config;
res.render(`${config.themeViews}customer-login`, {
title: 'Customer login',
config: req.app.config,
session: req.session,
message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'),
helpers: req.handlebars.helpers
});
});
2018-02-03 23:26:09 +10:00
// login the customer and check the password
2018-02-23 03:41:24 +10:00
router.post('/customer/login_action', async (req, res) => {
2019-07-12 18:06:34 +10:00
const db = req.app.db;
2018-02-03 23:26:09 +10:00
const customer = await db.customers.findOne({ email: mongoSanitize(req.body.loginEmail) });
2019-11-09 14:21:48 +10:00
// check if customer exists with that email
if(customer === undefined || customer === null){
res.status(400).json({
message: 'A customer with that email does not exist.'
});
return;
}
// we have a customer under that email so we compare the password
bcrypt.compare(req.body.loginPassword, customer.password)
.then((result) => {
if(!result){
// password is not correct
res.status(400).json({
2018-02-24 05:28:05 +10:00
message: 'Access denied. Check password and try again.'
2018-02-03 23:26:09 +10:00
});
2019-11-09 14:21:48 +10:00
return;
2018-02-03 23:26:09 +10:00
}
2019-11-09 14:21:48 +10:00
// Customer login successful
req.session.customerPresent = true;
req.session.customerId = customer._id;
req.session.customerEmail = customer.email;
req.session.customerCompany = customer.company;
req.session.customerFirstname = customer.firstName;
req.session.customerLastname = customer.lastName;
req.session.customerAddress1 = customer.address1;
req.session.customerAddress2 = customer.address2;
req.session.customerCountry = customer.country;
req.session.customerState = customer.state;
req.session.customerPostcode = customer.postcode;
req.session.customerPhone = customer.phone;
2019-11-09 14:21:48 +10:00
res.status(200).json({
message: 'Successfully logged in',
customer: customer
});
})
.catch((err) => {
res.status(400).json({
message: 'Access denied. Check password and try again.'
2018-02-03 23:26:09 +10:00
});
});
});
// customer forgotten password
router.get('/customer/forgotten', (req, res) => {
res.render('forgotten', {
title: 'Forgotten',
route: 'customer',
forgotType: 'customer',
2018-02-23 03:41:24 +10:00
config: req.app.config,
2018-02-03 23:26:09 +10:00
helpers: req.handlebars.helpers,
message: clearSessionValue(req.session, 'message'),
messageType: clearSessionValue(req.session, 'messageType'),
2018-02-03 23:26:09 +10:00
showFooter: 'showFooter'
});
});
// forgotten password
router.post('/customer/forgotten_action', apiLimiter, async (req, res) => {
2018-02-03 23:26:09 +10:00
const db = req.app.db;
2018-02-23 03:41:24 +10:00
const config = req.app.config;
2019-07-12 18:06:34 +10:00
const passwordToken = randtoken.generate(30);
2018-02-03 23:26:09 +10:00
// find the user
2019-11-09 14:21:48 +10:00
const customer = await db.customers.findOne({ email: req.body.email });
try{
if(!customer){
// if don't have an email on file, silently fail
res.status(200).json({
message: 'If your account exists, a password reset has been sent to your email'
});
return;
}
2019-11-09 14:21:48 +10:00
const tokenExpiry = Date.now() + 3600000;
await db.customers.updateOne({ email: req.body.email }, { $set: { resetToken: passwordToken, resetTokenExpiry: tokenExpiry } }, { multi: false });
// send forgotten password email
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
Please click on the following link, or paste this into your browser to complete the process:\n\n
${config.baseUrl}/customer/reset/${passwordToken}\n\n
If you did not request this, please ignore this email and your password will remain unchanged.\n`
};
// send the email with token to the user
// TODO: Should fix this to properly handle result
sendEmail(mailOpts.to, mailOpts.subject, mailOpts.body);
res.status(200).json({
message: 'If your account exists, a password reset has been sent to your email'
});
2019-11-09 14:21:48 +10:00
}catch(ex){
res.status(400).json({
message: 'Password reset failed.'
});
2019-11-09 14:21:48 +10:00
}
2018-02-03 23:26:09 +10:00
});
// reset password form
2019-11-09 14:21:48 +10:00
router.get('/customer/reset/:token', async (req, res) => {
2018-02-03 23:26:09 +10:00
const db = req.app.db;
// Find the customer using the token
2019-11-09 14:21:48 +10:00
const customer = await db.customers.findOne({ resetToken: req.params.token, resetTokenExpiry: { $gt: Date.now() } });
if(!customer){
req.session.message = 'Password reset token is invalid or has expired';
req.session.message_type = 'danger';
res.redirect('/forgot');
return;
}
// show the password reset form
res.render('reset', {
title: 'Reset password',
token: req.params.token,
route: 'customer',
config: req.app.config,
message: clearSessionValue(req.session, 'message'),
message_type: clearSessionValue(req.session, 'message_type'),
2019-11-09 14:21:48 +10:00
show_footer: 'show_footer',
helpers: req.handlebars.helpers
2018-02-03 23:26:09 +10:00
});
});
// reset password action
2019-11-09 14:21:48 +10:00
router.post('/customer/reset/:token', async (req, res) => {
2018-02-03 23:26:09 +10:00
const db = req.app.db;
// get the customer
2019-11-09 14:21:48 +10:00
const customer = await db.customers.findOne({ resetToken: req.params.token, resetTokenExpiry: { $gt: Date.now() } });
if(!customer){
req.session.message = 'Password reset token is invalid or has expired';
req.session.message_type = 'danger';
return res.redirect('/forgot');
}
// update the password and remove the token
const newPassword = bcrypt.hashSync(req.body.password, 10);
try{
await db.customers.updateOne({ email: customer.email }, { $set: { password: newPassword, resetToken: undefined, resetTokenExpiry: undefined } }, { multi: false });
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'
};
// TODO: Should fix this to properly handle result
sendEmail(mailOpts.to, mailOpts.subject, mailOpts.body);
2019-11-09 14:21:48 +10:00
req.session.message = 'Password successfully updated';
req.session.message_type = 'success';
return res.redirect('/checkout/payment');
2019-11-09 14:21:48 +10:00
}catch(ex){
console.log('Unable to reset password', ex);
req.session.message = 'Unable to reset password';
req.session.message_type = 'danger';
return res.redirect('/forgot');
}
2018-02-03 23:26:09 +10:00
});
// logout the customer
router.post('/customer/logout', (req, res) => {
// Clear our session
clearCustomer(req);
2018-02-03 23:26:09 +10:00
res.status(200).json({});
});
// logout the customer
router.get('/customer/logout', (req, res) => {
// Clear our session
clearCustomer(req);
res.redirect('/customer/login');
});
2018-02-03 23:26:09 +10:00
module.exports = router;