expressCart/routes/customer.js

309 lines
10 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 common = require('../lib/common');
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
// 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,
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()
};
const schemaResult = validateJson('customer', 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({
err: 'A customer already exists with that email address'
});
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);
// Customer creation successful
req.session.customer = newCustomer.insertedId;
const customerReturn = newCustomer.ops[0];
delete customerReturn.password;
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({
err: 'Customer creation failed.'
});
}
2018-02-03 23:26:09 +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;
2019-11-09 14:21:48 +10:00
const customer = await db.customers.findOne({ _id: common.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: common.clearSessionValue(req.session, 'message'),
messageType: common.clearSessionValue(req.session, 'messageType'),
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: common.clearSessionValue(req.session, 'message'),
messageType: common.clearSessionValue(req.session, 'messageType'),
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(common.getId(id.ref));
});
// 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: common.clearSessionValue(req.session, 'message'),
messageType: common.clearSessionValue(req.session, 'messageType'),
helpers: req.handlebars.helpers
2018-02-05 23:20:44 +10:00
});
});
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
2019-11-09 14:21:48 +10:00
const customer = await db.customers.findOne({ email: common.mongoSanitize(req.body.loginEmail) });
// 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.customer = customer;
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: common.clearSessionValue(req.session, 'message'),
messageType: common.clearSessionValue(req.session, 'messageType'),
showFooter: 'showFooter'
});
});
// forgotten password
2019-11-09 14:21:48 +10:00
router.post('/customer/forgotten_action', 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 });
// if we have a customer, set a token, expiry and email it
if(!customer){
req.session.message = 'Account does not exist';
req.session.message_type = 'danger';
res.redirect('/customer/forgotten');
return;
}
try{
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
common.sendEmail(mailOpts.to, mailOpts.subject, mailOpts.body);
req.session.message = 'An email has been sent to ' + req.body.email + ' with further instructions';
req.session.message_type = 'success';
res.redirect('/customer/forgotten');
}catch(ex){
req.session.message = 'Account does not exist';
req.session.message_type = 'danger';
res.redirect('/customer/forgotten');
}
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: common.clearSessionValue(req.session, 'message'),
message_type: common.clearSessionValue(req.session, 'message_type'),
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
common.sendEmail(mailOpts.to, mailOpts.subject, mailOpts.body);
req.session.message = 'Password successfully updated';
req.session.message_type = 'success';
return res.redirect('/pay');
}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) => {
req.session.customer = null;
res.status(200).json({});
});
module.exports = router;