forked from anushatulsyan/expressCart
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcustomer.js
308 lines (275 loc) · 10.9 KB
/
customer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
const express = require('express');
const router = express.Router();
const colors = require('colors');
const randtoken = require('rand-token');
const bcrypt = require('bcryptjs');
const common = require('../lib/common');
const { restrict } = require('../lib/auth');
// insert a customer
router.post('/customer/create', (req, res) => {
const db = req.app.db;
const doc = {
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,
password: bcrypt.hashSync(req.body.password, 10),
created: new Date()
};
// check for existing customer
db.customers.findOne({ email: req.body.email }, (err, customer) => {
if(customer){
res.status(400).json({
err: 'A customer already exists with that email address'
});
return;
}
// email is ok to be used.
db.customers.insertOne(doc, (err, newCustomer) => {
if(err){
if(newCustomer){
console.error(colors.red('Failed to insert customer: ' + err));
res.status(400).json({
err: 'A customer already exists with that email address'
});
return;
}
console.error(colors.red('Failed to insert customer: ' + err));
res.status(400).json({
err: 'Customer creation failed.'
});
return;
}
// Customer creation successful
req.session.customer = newCustomer.ops[0];
res.status(200).json({
message: 'Successfully logged in',
customer: newCustomer
});
});
});
});
// render the customer view
router.get('/admin/customer/view/:id?', restrict, (req, res) => {
const db = req.app.db;
db.customers.findOne({ _id: common.getId(req.params.id) }, (err, customer) => {
if(err){
console.info(err.stack);
}
// 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
});
});
});
// customers list
router.get('/admin/customers', restrict, (req, res) => {
const db = req.app.db;
db.customers.find({}).limit(20).sort({ created: -1 }).toArray((err, customers) => {
// 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
});
});
});
// Filtered customers list
router.get('/admin/customers/filter/:search', restrict, (req, res, next) => {
const db = req.app.db;
const searchTerm = req.params.search;
const customersIndex = req.app.customersIndex;
const lunrIdArray = [];
customersIndex.search(searchTerm).forEach((id) => {
lunrIdArray.push(common.getId(id.ref));
});
// we search on the lunr indexes
db.customers.find({ _id: { $in: lunrIdArray } }).sort({ created: -1 }).toArray((err, customers) => {
if(err){
console.error(colors.red('Error searching', err));
}
// If API request, return json
if(req.apiAuthenticated){
return res.status(200).json({
customers
});
}
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
});
});
});
// login the customer and check the password
router.post('/customer/login_action', async (req, res) => {
const db = req.app.db;
db.customers.findOne({email: common.mongoSanitize(req.body.loginEmail)}, (err, customer) => { // eslint-disable-line
if(err){
// An error accurred
return res.status(400).json({
message: 'Access denied. Check password and try again.'
});
}
// check if customer exists with that email
if(customer === undefined || customer === null){
return res.status(400).json({
message: 'A customer with that email does not exist.'
});
}
// 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
return res.status(400).json({
message: 'Access denied. Check password and try again.'
});
}
// Customer login successful
req.session.customer = customer;
return res.status(200).json({
message: 'Successfully logged in',
customer: customer
});
})
.catch((err) => {
return res.status(400).json({
message: 'Access denied. Check password and try again.'
});
});
});
});
// customer forgotten password
router.get('/customer/forgotten', (req, res) => {
res.render('forgotten', {
title: 'Forgotten',
route: 'customer',
forgotType: 'customer',
config: req.app.config,
helpers: req.handlebars.helpers,
message: common.clearSessionValue(req.session, 'message'),
messageType: common.clearSessionValue(req.session, 'messageType'),
showFooter: 'showFooter'
});
});
// forgotten password
router.post('/customer/forgotten_action', (req, res) => {
const db = req.app.db;
const config = req.app.config;
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){
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
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';
return res.redirect('/customer/forgotten');
});
}else{
req.session.message = 'Account does not exist';
res.redirect('/customer/forgotten');
}
});
});
// reset password form
router.get('/customer/reset/:token', (req, res) => {
const db = req.app.db;
// Find the customer using the token
db.customers.findOne({ resetToken: req.params.token, resetTokenExpiry: { $gt: Date.now() } }, (err, customer) => {
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
});
});
});
// reset password action
router.post('/customer/reset/:token', (req, res) => {
const db = req.app.db;
// get the customer
db.customers.findOne({ resetToken: req.params.token, resetTokenExpiry: { $gt: Date.now() } }, (err, customer) => {
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);
db.customers.update({ email: customer.email }, { $set: { password: newPassword, resetToken: undefined, resetTokenExpiry: undefined } }, { multi: false }, (err, numReplaced) => {
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');
});
return'';
});
});
// logout the customer
router.post('/customer/logout', (req, res) => {
req.session.customer = null;
res.status(200).json({});
});
module.exports = router;