-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathserver.js
More file actions
674 lines (647 loc) · 17.6 KB
/
server.js
File metadata and controls
674 lines (647 loc) · 17.6 KB
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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
const path = require("path");
const express = require("express");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const cors = require("cors");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const fileUpload = require("express-fileupload");
const stripe = require("stripe")("sk_test_K04zveK9MnFXMgiIxhHv6mIa");
const port = process.env.PORT || 3001;
const STATUS_USER_ERROR = 422;
const STATUS_SERVER_ERROR = 500;
const STATUS_UNAUTHORIZED_ERROR = 401;
const corsOptions = {
origin: true,
methods: "GET, HEAD, PUT, PATCH, POST, DELETE",
preflightContinue: true,
optionsSuccessStatus: 204,
credentials: true // enable set cookie
};
const Users = require("./server/invoice/userModel.js");
const Invoices = require("./server/invoice/invModel.js");
const server = express();
server.use(express.static(path.resolve(__dirname, "./client/build")));
server.use(bodyParser.urlencoded({ extended: false })); // added
server.use(bodyParser.json());
server.use(fileUpload({ limits: { fileSize: 400 * 1024 } }));
server.use(cors());
require("dotenv").config();
mongoose.Promise = global.Promise;
mongoose
.connect(process.env.MONGO_URI)
// .connect("mongodb://localhost:27017/users")
.then(function(db) {
console.log("All your dbs belong to us!");
server.listen(port, function() {
console.log("server running on port 3001");
});
})
.catch(function(err) {
console.log("DB connection failed..", err.message);
});
/**
* Middleware for token verification
*/
const verifyToken = (req, res, next) => {
const tkn = req.get("Authorization");
if (!tkn) {
return res
.status(STATUS_UNAUTHORIZED_ERROR)
.json({ err: "You are not authorized to do this request" });
}
jwt.verify(tkn, process.env.SECRET, (err, decoded) => {
if (err)
return res
.status(STATUS_UNAUTHORIZED_ERROR)
.json({ err: "You are not authorized to do this request" });
return next();
});
};
/**
* CRUD for Users - Users are who we bill for using our app
*/
let userName, email, hashPassword;
/**
* Update a User
*/
server.put("/users/:id", function(req, res) {
const { dateAccountOpened, userName, email, hashPassword } = req.body;
Users.findByIdAndUpdate(req.params.id, { $set: req.body }, function(
err,
users
) {
if (err) {
res.status(STATUS_USER_ERROR).json({ error: "Could not update user" });
} else {
res.status(200).json({ success: "User updated!" });
}
});
});
/**
* Update a User Paid Flag ( oneTimePaid )
*/
server.put("/paidFlag", function(req, res) {
const { oneTimePaid } = req.body;
const userId = req.query.userId;
Users.findByIdAndUpdate(req.params.id, { $set: req.body }, function(
err,
users
) {
if (err) {
res
.status(STATUS_USER_ERROR)
.json({ error: "Could not update paidFlag" });
} else {
console.log("hello!", Users.oneTimePaid);
res.status(200).json({ success: "PaidFlag updated!" });
}
});
});
/**
* Get all Users
*/
server.get("/users", function(req, res) {
Users.find({}, function(err, users) {
if (err) {
res
.status(STATUS_SERVER_ERROR)
.json({ error: "Could not retrieve users" });
} else {
res.status(200).json(users);
}
});
});
/**
* Get Users by _id
*/
server.get("/users/:id", function(req, res) {
const { id } = req.params;
Users.findById(id, function(err, users) {
if (err) {
res.status(STATUS_USER_ERROR).json({ error: "Could not retrieve user" });
} else {
res.status(200).json(users);
}
});
});
/**
* Delete Users by _id
*/
server.delete("/users/:id", function(req, res) {
const { id } = req.params;
Users.findByIdAndRemove(id, function(err, users) {
if (err) {
res.status(STATUS_USER_ERROR).json({ error: "Could not delete user" });
} else {
res.status(200).json({ success: "User deleted!" });
}
});
});
/**
* CRUD for Invoices
*/
let userId,
invCustomerAddress,
invNumber,
invDate,
invDueDate,
invBillableItems,
invDiscount,
invTax,
invDeposit,
invShipping,
invComment,
invTerms,
invPaidFor;
/**
* Get All Invoices
*/
server.get("/invoices", verifyToken, (req, res) => {
const userId = req.query.userId;
Invoices.find({ usersId: userId }, (err, invoices) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ error: "Could not retrieve invoices" });
}
return res.status(200).json(invoices);
});
});
// /**
// * Post Invoices
// */
server.post("/new", (req, res) => {
const userId = req.query.userId;
const tkn = req.get("Authorization");
const {
invCustomerAddress,
invNumber,
invNumberExtension,
invDate,
invDueDate,
invBillableItems,
invDiscount,
invTax,
invDeposit,
invShipping,
invComment,
invTerms,
invPaidFor
} = req.body;
if (!invNumber) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "Could not create invoice due to missing fields" });
}
const newInv = new Invoices({
usersId: userId,
invCustomerAddress,
invNumber,
invNumberExtension,
invDate,
invDueDate,
invBillableItems,
invDiscount,
invTax,
invDeposit,
invShipping,
invComment,
invTerms,
invPaidFor
});
newInv.save((err, invoice) => {
if (err) {
console.log(err);
return res
.status(STATUS_SERVER_ERROR)
.json({ error: "Could not create the invoice." });
}
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
user.currentInvoiceNumber += 1;
user.save((err, updatedUser) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't save current Invoice Number" });
}
res.status(201).send({ invoiceId: invoice._id });
});
});
});
});
/**
* Update an Invoice
*/
server.put("/updated-invoice", verifyToken, (req, res) => {
const invoiceId = req.query.invoiceId;
const {
invCustomerAddress,
invNumber,
invNumberExtension,
invDate,
invDueDate,
invBillableItems,
invDiscount,
invTax,
invDeposit,
invShipping,
invComment,
invTerms,
invPaidFor
} = req.body;
Invoices.findById(invoiceId, (err, invoice) => {
if (err) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "Could not update invoice" });
}
invoice.invCustomerAddress = invCustomerAddress;
invoice.invNumber = invNumber;
invoice.invNumberExtension = invNumberExtension;
invoice.invDate = invDate;
invoice.invDueDate = invDueDate;
invoice.invBillableItems = invBillableItems;
invoice.invDiscount = invDiscount;
invoice.invTax = invTax;
invoice.invDeposit = invDeposit;
invoice.invShipping = invShipping;
invoice.invComment = invComment;
invoice.invTerms = invTerms;
invoice.invPaidFor = invPaidFor;
invoice.save((err, updatedInvoice) => {
if (err) {
return res.status(STATUS_SERVER_ERROR);
json({ err: "couldn't save changes" });
}
res.status(200).json(updatedInvoice);
});
});
});
/**
* Get Invoices by _id
*/
server.get("/invoice", verifyToken, (req, res) => {
const invoiceId = req.query.invoiceId;
// const tkn = req.get("Authorization");
Invoices.findById(invoiceId, (err, invoice) => {
if (err) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "Could not retrieve invoice" });
}
res.status(200).json(invoice);
});
});
/**
* Delete Invoices by _id
*/
server.delete("/invoices", verifyToken, (req, res) => {
const invoiceId = req.query.invoiceId;
Invoices.findByIdAndRemove(invoiceId, (err, invoices) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ error: "Could not delete invoice" });
}
res.status(200).json({ message: "Invoice deleted!" });
});
});
/**
* User authentication endpoints
*/
/**
* Middleware for password hashing
*/
const BCRYPT_COST = 11;
const hashedPassword = (req, res, next) => {
const { password } = req.body;
if (!password) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "Password can't be blank" });
}
bcrypt
.hash(password, BCRYPT_COST)
.then(pw => {
req.password = pw;
next();
})
.catch(err => {
throw new Error("The password wasn't hashed");
});
};
/**
* Create a new user
*/
server.post("/new-user", hashedPassword, (req, res) => {
const { email } = req.body;
if (!email) {
return res.status(STATUS_USER_ERROR).json({ error: "Email is required" });
}
// since our users can disable js on the client
// and email address serves as a unique username
// this validation will be enough
const isEmailValid = /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/;
if (!isEmailValid.test(email)) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "The Email Address is in an invalid format." });
}
const hashPassword = req.password;
const newUser = new Users({ email, hashPassword });
newUser.save((err, savedUser) => {
if (err) {
if (err.code === 11000) {
return res.status(409).json({ error: "This email is already taken" });
}
return res
.status(STATUS_SERVER_ERROR)
.json({ error: "User wasn't saved to the database" });
}
const token = jwt.sign({ id: savedUser._id }, process.env.SECRET);
res.status(200).send({ token, userId: savedUser._id });
});
});
/**
* User Login
*/
server.post("/login", (req, res) => {
const { email, password } = req.body;
if (!email) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "Email can't be blank" });
}
if (!password) {
return res
.status(STATUS_USER_ERROR)
.json({ error: "Password can't be blank" });
}
Users.findOne({ email }, (err, user) => {
if (err || user === null) {
return res
.status(STATUS_SERVER_ERROR)
.json({ error: "Incorrect email/password combination" });
}
const hashedPw = user.hashPassword;
bcrypt
.compare(password, hashedPw)
.then(response => {
if (!response) throw new Error("Password hashes weren't compared");
})
.then(() => {
const token = jwt.sign({ id: user._id }, process.env.SECRET);
res.status(200).send({ token, userId: user._id });
})
.catch(error => {
res
.status(STATUS_SERVER_ERROR)
.json({ error: "Incorrect creditentials" });
});
});
});
/**
* Token validation for the front-end
*/
server.get("/jwt", (req, res) => {
const tkn = req.get("Authorization");
if (!tkn)
return res.status(STATUS_UNAUTHORIZED_ERROR).json({ authenticated: false });
jwt.verify(tkn, process.env.SECRET, (err, decoded) => {
if (err)
return res
.status(STATUS_UNAUTHORIZED_ERROR)
.json({ authenticated: false });
res.status(200).json({ authenticated: true });
});
});
/**
* Stripe
*/
server.post("/api/checkout", (req, res) => {
console.log("checkout starting...");
const { token, subscription, one } = req.body;
const userId = req.query.userId;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
const amount = subscription ? "999" : "99";
if (!token) return res.json({ err: "Payment Failed" });
if (one === false) {
user.subscription = true;
user.save();
stripe.plans.create(
{
amount: amount,
currency: "usd",
interval: "year",
product: "prod_Ch5UI61HmNtmds",
nickname: user.email
},
(err, charge) => {
if (err) return res.json({ err: "Payment Failed", error: err });
res.send(charge);
}
);
} else {
user.oneTimePaid = true;
user.save();
stripe.charges.create(
{
amount: amount,
currency: "usd",
description: user.email,
source: token
},
(err, charge) => {
if (err) return res.json({ err: "Payment Failed", error: err });
res.send(charge);
}
);
}
});
});
/**
* Logo uploading
*/
server.put("/upload", verifyToken, (req, res) => {
const imageFile = req.files.logo;
if (imageFile.truncated) {
return res
.status(413)
.json({ err: "Your image size exceeds max limit of 0.4mb" });
}
const supportedMimeTypes = ["image/jpeg", "image/png"];
const contentType = imageFile.mimetype;
if (supportedMimeTypes.indexOf(contentType) === -1) {
return res.status(STATUS_USER_ERROR).json({
err: "You are permitted to upload the following image types jpeg and png"
});
}
const userId = req.query.userId;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
const binaryData = imageFile.data.toString("base64");
const logo = { binaryData, contentType };
user.logo = logo;
user.save((err, updatedUser) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't save changes" });
}
res.status(200).json(updatedUser.logo);
});
});
});
/**
* Get logo and company name
*/
server.get("/logo", verifyToken, (req, res) => {
const userId = req.query.userId;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
const userLogo = user.logo;
if (!userLogo.contentType) {
return res.status(200).json({ message: "Logo is not selected" });
}
const companyName = user.companyName;
const companyAddress = user.companyAddress;
const currentInvoiceNumber = user.currentInvoiceNumber;
res
.status(200)
.json({ userLogo, companyName, companyAddress, currentInvoiceNumber });
});
});
/**
* Company name update
*/
server.put("/company-name", verifyToken, (req, res) => {
const userId = req.query.userId;
const companyName = req.body.companyName;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
user.companyName = companyName;
user.save((err, updatedUser) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't save changes" });
}
res.status(200).json(updatedUser.companyName);
});
});
});
/**
* Company address update
*/
server.put("/company-address", verifyToken, (req, res) => {
const userId = req.query.userId;
const companyAddress = req.body.companyAddress;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
user.companyAddress = companyAddress;
user.save((err, updatedUser) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't save changes" });
}
res.status(200).json(updatedUser.companyAddress);
});
});
});
/**
* Current invoice number update
*/
server.put("/invoice-number", verifyToken, (req, res) => {
const userId = req.query.userId;
const currentInvoiceNumber = req.body.invoiceNumber;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
user.currentInvoiceNumber = currentInvoiceNumber;
user.save((err, updatedUser) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't save changes" });
}
res.status(200).json(updatedUser.currentInvoiceNumber);
});
});
});
/**
* Change User Password
*/
server.put("/new-password", verifyToken, (req, res) => {
const userId = req.query.userId;
const { oldpassword, newpassword } = req.body;
Users.findById(userId, (err, user) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't find user" });
}
const hashedPw = user.hashPassword;
bcrypt
.compare(oldpassword, hashedPw)
.then(response => {
if (!response) throw new Error("Password hashes weren't compared");
})
.then(() => {
bcrypt
.hash(newpassword, BCRYPT_COST)
.then(pw => {
user.hashPassword = pw;
user.save((err, updatedUser) => {
if (err) {
return res
.status(STATUS_SERVER_ERROR)
.json({ err: "Couldn't save changes" });
}
res.status(200).json({ message: "The password was changed" });
});
})
.catch(err => {
throw new Error("The password wasn't hashed");
});
})
.catch(error => {
res
.status(STATUS_SERVER_ERROR)
.json({ error: "Incorrect creditentials" });
});
});
});
server.get("*", (request, response) => {
response.sendFile(path.resolve(__dirname, "./client/build", "index.html"));
});