-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
1216 lines (1003 loc) · 31.6 KB
/
server.js
File metadata and controls
1216 lines (1003 loc) · 31.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
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ANCHOR Imports
// Environment config
require("dotenv").config();
// External dependencies
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const bcrypt = require("bcryptjs");
const jwt = require("jsonwebtoken");
const postmark = require("postmark");
const crypto = require("crypto");
const https = require("https");
const port = process.env.PORT || 5000;
const fs = require("fs");
const path = require("path");
// HTTPS credentials - Uncomment on server
// const credentials = {
// key: fs.readFileSync("/etc/letsencrypt/live/overcastly.app/privkey.pem", "utf8"),
// cert: fs.readFileSync("/etc/letsencrypt/live/overcastly.app/cert.pem", "utf8"),
// ca: fs.readFileSync("/etc/letsencrypt/live/overcastly.app/chain.pem", "utf8"),
// };
// Database
const { MongoClient, ObjectId } = require("mongodb");
const url = process.env.DB_URL;
const client = new MongoClient(url);
client.connect();
const db = client.db("Overcastly");
// Express
const app = express();
// Middleware
app.use(cors());
app.use(express.json( { limit: '8mb' } ));
// Consts
const JWT_SECRET = process.env.JWT_SECRET || "jwt-secret-fallback-pls-make-sure-env-has-it";
// verify jwt token (middleware)
const authToken = (req, res, next) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "Authentication failed" });
}
jwt.verify(token, JWT_SECRET, (err, user) => {
if (err) {
return res
.status(403)
.json({ error: "Invalid token" });
}
req.user = user;
next();
});
};
// ANCHOR Authenticate
// Codes:
// 200 (authenticated)
// 401 (authentication fails)
// 403 (invalid token)
app.get("/api/authenticate", async (req, res) => {
const authHeader = req.headers["authorization"];
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
return res.status(401).json({ error: "Authentication failed" });
}
jwt.verify(token, JWT_SECRET, (err) => {
if (err) {
return res.status(403).json({ error: "Invalid token" });
}
else {
return res.status(200).json({ message: "Successfully authenticated"} )
}
});
})
// ANCHOR Login
// Codes:
// 200 (user logged in)
// 400 (missing input fields)
// 401 (invalid inputs)
// 500 (generic error)
app.post("/api/login", async (req, res) => {
const { login, password } = req.body;
if (!login || !password) {
return res
.status(400)
.json({ error: "Not all fields populated" });
}
// user can provide username or email
try {
const user = await db.collection("Users").findOne({
$or: [{ username: login }, { email: login }],
});
if (!user) {
return res.status(401).json({ error: "Invalid credentials" });
}
const checkPassword = await bcrypt.compare(password, user.password);
if (!checkPassword) {
return res.status(401).json({ error: "Invalid credentials" });
}
if (user.hasOwnProperty('active') && user.active == false) {
return res.status(401).json({
userId: user._id,
active: false,
error: "User has not yet been activated"
});
}
const token = jwt.sign(
{
userId: user._id,
username: user.username,
email: user.email,
},
JWT_SECRET,
{ expiresIn: "24h" }
);
return res.status(200).json({
token,
userId: user._id,
active: true,
// username: user.username,
// email: user.email,
message: "User logged in",
});
} catch (error) {
return res.status(500).json({ error: "Server error while attempting login" });
}
});
// ANCHOR (P) Create Post
// Codes:
// 201 (post created)
// 400 (missing input fields)
// 500 (generic error)
//
app.post("/api/createpost", authToken, async (req, res) => {
// incoming: title, body, image, latitude, longitude, authorId, tags
// outgoing: error
const { title, body, image, latitude, longitude, tags } = req.body;
// Check that necessary fields are present
if (!title || !body || !latitude || !longitude) {
return res.status(400).json({ error: "Not all necessary fields are present" });
}
// Fetch info for a new post
const newPost = {
title: title,
body: body,
image: image,
latitude: latitude,
authorId: req.user.userId, // grabbing it from user auth
longitude: longitude,
tags: tags,
createdAt: new Date(), // might be useful : )
};
try {
const result = await db.collection("Posts").insertOne(newPost);
return res.status(201).json({ postId: result["insertedId"] });
} catch (error) {
return res.status(500).json( {error: "Could not make post" });
}
});
// ANCHOR (R) Create Reply
// Codes:
// 201 (reply created)
// 400 (missing input fields)
// 500 (generic error)
//
app.post("/api/createreply", authToken, async (req, res) => {
// incoming: body, image, authorId, originalPostId
// outgoing: error
const { body, image, originalPostId } = req.body;
// Check that necessary fields are present
if (!body || !originalPostId) {
return res.status(400).json({ error: "Not all necessary fields are present" });
}
// Fetch info for a new post
const newPost = {
body: body,
image: image,
authorId: new ObjectId(req.user.userId),
replyTo: new ObjectId(originalPostId),
createdAt: new Date(),
};
try {
const result = db.collection("Posts").insertOne(newPost);
return res.status(201).json({ message: "Reply successfully created" });
} catch (e) {
return res.status(500).json({ error: "Reply could not be made" });
}
});
// ANCHOR (P/R) Search Posts
// Codes:
// 200 (no error)
// 500 (generic error)
//
app.post("/api/searchposts", async (req, res) => {
// incoming: title, body, authorId, tags
// outgoing: title, body, image, latitude, longitude, authorId, tags
// Partial matching w/ regex
const { title, body, authorId, tags } = req.body;
try {
let results = [];
const resultsBody = await db
.collection("Posts")
.find({
$or: [
{ title: { $regex: title.trim() + ".*", $options: "i" } },
{ body: { $regex: body.trim() + ".*", $options: "i" } },
{ authorId: authorId },
],
})
.toArray();
const resultsTags = await db
.collection("Posts")
.find({ tags: tags })
.toArray();
// Match the tags up
if (tags.length > 0) {
results = resultsBody.concat(resultsTags);
} else {
results = resultsBody;
}
let ret = [];
// Push all matches to the output
for (let i = 0; i < results.length; i++) {
ret.push(results[i]);
}
return res.status(200).json(ret);
} catch (error) {
return res.status(500).json({ error: "Failed to search for posts and/or replies" });
}
});
// ANCHOR (P/R) Generalized Post Search
// Codes:
// 200 (no error)
// 500 (generic error)
//
app.post("/api/generalsearchposts", async (req, res) => {
// incoming: search
// outgoing: title, body, image, latitude, longitude, authorId, tags
// Partial matching w/ regex
const { search } = req.body;
try {
const resultsBody = await db
.collection("Posts")
.find({
$or: [
{ title: { $regex: search.trim() + ".*", $options: "i" } },
// { body: { $regex: search.trim() + ".*", $options: "i" } }
],
})
.toArray();
return res.status(200).json(resultsBody);
} catch (error) {
return res.status(500).json({ error: "Failed to search for posts and/or replies" });
}
});
// ANCHOR (P) Get Local Posts
// Codes:
// 200 (local posts found)
// 400 (input fields missing)
// 500 (generic error)
//
app.post("/api/getlocalposts", async (req, res) => {
// incoming: latitude, longitude, distance
// outgoing: id, title, body, image, latitude, longitude, authorId, tags
// returns array of posts within distance of latitude and longitude
const { latitude, longitude, distance } = req.body;
// Make sure lat/long and distance are all present
if (!latitude || !longitude || !distance) {
return res.status(400).json({error: "Not all necessary fields are present"});
}
try {
// Get all posts
const results = await db
.collection("Posts")
.find({})
.sort([["_id", -1]])
.toArray();
let ret = [];
// Iterate through all posts
for (let i = 0; i < results.length; i++) {
// Calculate distance for endpoint
let calcDistance = Math.sqrt(
(results[i].latitude - latitude) ** 2 +
(results[i].longitude - longitude) ** 2
);
// If it's too far or doesn't have the necessary fields, skip
if (
calcDistance > distance ||
!(
results[i].hasOwnProperty("latitude") &&
results[i].hasOwnProperty("longitude")
)
)
continue;
ret.push({ ...results[i] });
}
return res.status(200).json(ret);
} catch (error) {
return res.status(500).json({error: "Could not get local posts"});
}
});
// ANCHOR (P) Get Pin GeoJSON
// Codes:
// 200 (pins found)
// 400 (missing inputs)
// 500 (generic error)
//
app.get("/api/getpins", async (req, res) => {
// incoming: nonr
// outgoing: id, title, body, image, latitude, longitude, authorId, tags
// returns array of posts within distance of latitude and longitude
try {
// Fetch posts
const results = await db
.collection("Posts")
.find({})
.sort([["_id", -1]])
.toArray();
// Stack for elements
let features = [];
// Iterate through all posts
for (let i = 0; i < results.length; i++) {
// Make sure we have lat/long data for this post
if (
!(
results[i].hasOwnProperty("latitude") &&
results[i].hasOwnProperty("longitude")
)
)
continue;
// Populate generic structure of GeoJSON
let newFeature = new Object();
newFeature.type = "Feature"
newFeature.geometry = new Object();
newFeature.properties = new Object();
// Populate geometry
newFeature.geometry.type = "Point";
newFeature.geometry.coordinates = [results[i].longitude, results[i].latitude];
// Populate properties
newFeature.properties.id = results[i]._id;
newFeature.properties.title = results[i].title;
newFeature.properties.body = results[i].body;
newFeature.properties.author = results[i].authorId;
// Push all the content associated
features.push({ ...newFeature });
}
const geoJSON = {
"type": "FeatureCollection",
"features": features
}
return res.status(200).json(geoJSON);
} catch (error) {
return res.status(500).json({error: "Could not get pins"});
}
});
// ANCHOR (P/R) Get Post
// Codes:
// 200 (post or reply found)
// 404 (post or reply matching ID not found)
// 500 (generic error)
//
app.get("/api/posts/:_id", async (req, res) => {
// incoming: post ObjectId (used in url)
// outgoing: id, title, body, image, latitude, longitude, authorId, tags
try {
// Fetch posts matching the id
const postId = req.params._id;
const results = await db.collection("Posts").find({ _id: new ObjectId(postId) }).toArray();
// If not found, return 404
if (results.length == 0)
{
return res.status(404).json({ error: "Post or reply not found" });
}
// Post found! Return it.
return res.status(200).json(results[0]);
} catch (error) {
return res.status(500).json({ error: "Couldn't get post or reply"});
}
});
// ANCHOR (R) Get Replies
// Codes:
// 200 (replies found)
// 204 (no replies found)
// 404 (original post not found)
// 500 (generic error)
//
app.get("/api/posts/:_id/getreplies", async (req, res) => {
// incoming: replyTo (string)
// outgoing: _id, authorId, body, image
// returns array of replies to the given post
try {
const postId = req.params._id;
// Ensure the post exists
const foundPost = await db.collection("Posts").findOne({ _id: new ObjectId(postId) });
if (!foundPost) {
return res.status(404).json({ error: "No original post found: cannot get replies" });
}
// Get all replies to the post, if it exists
const results = await db.collection('Posts').find({ "replyTo": new ObjectId(postId) }).sort([["_id"]]).toArray();
let ret = [];
for (let i = 0; i < results.length; i++) {
// Fetch all reply components
let outId = results[i]._id;
let outAuthorId = results[i].authorId;
let outBody = results[i].body;
let outImage = results[i].image;
// Push to the output
ret.push({ _id: outId, authorId: outAuthorId, body: outBody, image: outImage });
}
return res.status(200).json(ret);
} catch(error) {
return res.status(500).json({ error: "Failed to get replies for post" });
}
});
// ANCHOR (P) Update Post
// Codes:
// 200 (post updated)
// 400 (missing input fields)
// 403 (ownership error)
// 404 (post not found)
// 500 (generic error)
//
app.put("/api/updatepost/:_id", authToken, async (req, res) => {
// /:_id
// incoming: new post data
// outgoing: success or error
try {
const db = client.db("Overcastly");
let _id = req.params._id;
const { title, body, image, latitude, longitude, tags } = req.body;
if (!title && !body && !image && !latitude && !longitude && !tags) {
return res.status(400).json({ error: "No fields provided :(" });
}
let readPost = await db
.collection("Posts")
.findOne({ _id: new ObjectId(_id) });
if (!readPost) {
return res.status(404).json({ error: "Post not found :(" });
}
// check if logged in user is author of post
if (readPost.authorId.toString() !== req.user.userId.toString()) {
return res
.status(403)
.json({ error: "Ownership error" });
}
const result = await db.collection("Posts").updateOne(
{ _id: new ObjectId(_id) },
{
$set: {
...req.body,
updatedAt: new Date(),
},
}
);
return res.status(200).json({ message: "Post updated" });
} catch (error) {
return res.status(500).json({ error: "Failed to update post" });
}
});
// ANCHOR (R) Update Reply
// Codes:
// 200 (reply updated)
// 400 (missing input fields)
// 403 (ownership error)
// 404 (reply not found)
// 500 (generic error)
//
app.put("/api/updatereply/:_id", authToken, async (req, res) => {
// /:_id
// incoming: new reply data
// outgoing: success or error
try {
const db = client.db("Overcastly");
let _id = req.params._id;
const { title, body, image } = req.body;
if (!title && !body && !image) {
return res.status(400).json({ error: "No fields provided :(" });
}
let readPost = await db.collection("Posts").findOne({
_id: new ObjectId(_id),
replyTo: { $exists: true }, // verify it's a reply and not its own post
});
if (!readPost) {
return res.status(404).json({ error: "Reply not found :(" });
}
if (readPost.authorId.toString() !== req.user.userId.toString()) {
return res
.status(403)
.json({ error: "Ownership error" });
}
const updateFields = {
...(title && { title }),
...(body && { body }),
...(image && { image }),
updatedAt: new Date(),
};
const result = await db
.collection("Posts")
.updateOne({ _id: new ObjectId(_id) }, { $set: updateFields });
return res.status(200).json({ message: "Reply updated" });
} catch (error) {
return res.status(500).json({ error: "Failed to update reply" });
}
});
// ANCHOR (P/R) Delete Post
// Codes:
// 204 (post or reply deleted)
// 403 (ownership error)
// 404 (post or reply not found) x2
// 500 (generic error)
//
app.delete("/api/deletepost/:_id", authToken, async (req, res) => {
// incoming: post Id
// outgoing: success or error
// Pablo - why are there two spots that can trigger a 404?
try {
const db = client.db("Overcastly");
let _id = req.params._id;
const foundPost = await db
.collection("Posts")
.findOne({ _id: new ObjectId(_id) });
if (!foundPost) {
return res
.status(404)
.json({ error: "Can't delete a post or reply that doesn't exist" });
}
// check if logged in user is author of post
if (foundPost.authorId.toString() !== req.user.userId.toString()) {
return res
.status(403)
.json({ error: "Ownership error" });
}
// delete replies
await db.collection("Posts").deleteMany({ replyTo: new ObjectId(_id) });
// delete original post
let delResult = await db
.collection("Posts")
.deleteOne({ _id: new ObjectId(_id) });
if (delResult.deletedCount === 0) {
return res
.status(404)
.json({ error: "Could not delete - post or reply does not exist" });
}
return res.status(204).json({ message: "Post or reply deleted" });
} catch (e) {
return res.status(500).json({ error: "Failed to delete post or reply" });
}
});
// ANCHOR Register User (Deprecated)
// Codes:
// 201 (user registered)
// 400 (missing input fields)
// 409 (username or email already used)
// 500 (generic error)
app.post("/api/registeruser", async (req, res) => {
// incoming: username, password, firstName, lastName, email
// outgoing: error
const { username, password, firstName, lastName, email } = req.body;
if (!username || !password || !firstName || !lastName || !email) {
return res.status(400).json({ error: "Missing some register fields :(" });
}
try {
const existingUser = await db.collection("Users").findOne({
$or: [{ username }, { email }],
});
if (existingUser) {
const error =
existingUser.username === username
? "Username already exists!"
: "Email has already been registered to an account";
return res.status(409).json({ error });
}
const hashedPasswd = await bcrypt.hash(password, 10);
const newUser = {
username,
password: hashedPasswd,
firstName,
lastName,
email,
};
await db.collection("Users").insertOne(newUser);
return res
.status(201)
.json({ message: "User registered successfully >W<" });
} catch (e) {
return res.status(500).json({ error: "A servar ewwow happend ;(" });
}
});
// ANCHOR Begin User Registration
// Codes:
// 201 (user registered)
// 400 (missing input fields)
// 409 (username or email already used)
// 500 (generic error)
app.post("/api/initialregisteruser", async (req, res) => {
// incoming: username, password, firstName, lastName, email
// outgoing: error
const { username, password, firstName, lastName, email } = req.body;
if (!username || !password || !firstName || !lastName || !email) {
return res.status(400).json({ error: "Missing some register fields" });
}
try {
const existingUser = await db.collection("Users").findOne({
$or: [{ username }, { email }],
});
if (existingUser) {
const error =
existingUser.username === username
? "Username already exists!"
: "Email has already been registered to an account";
return res.status(409).json({ error });
}
const hashedPasswd = await bcrypt.hash(password, 10);
const userPin = Math.floor(Math.random() * 8999) + 1000;
const newUser = {
username,
password: hashedPasswd,
firstName,
lastName,
email,
active: false,
userPin
};
let key = process.env.POSTMARK_KEY;
if (key != "0") {
const client = new postmark.ServerClient(key);
client.sendEmailWithTemplate({
"TemplateId": 38227984,
"From": "noreply@overcastly.app",
"To": email,
"TemplateModel": { product_url: "overcastly.app", product_name:"Overcastly", company_name:"Overcastly", company_address:"Orlando, FL", name:firstName, user_pin:userPin.toString(), email:email, username:username}
});
}
let userVerification = await db.collection("Users").insertOne(newUser);
delete userVerification.acknowledged;
userVerification.pin = userPin;
return res
.status(201)
.json(userVerification);
} catch (e) {
return res.status(500).json({ error: "Server error in creation of user" });
}
});
// ANCHOR Complete User Registration
// Codes:
// 200 (user registration complete)
// 400 (missing input fields)
// 403 (incorrect PIN given)
// 404 (user not found)
// 409 (user already registered)
// 500 (generic error)
app.post("/api/completeregisteruser/:_id", async (req, res) => {
// incoming: userPin, id
// outgoing: error
const { userPin } = req.body;
let _id = req.params._id;
// Verify necessary fields are provided
if (!userPin || !_id) {
return res.status(400).json({ error: "No user verification pin or ID provided" });
}
try {
// Fetch the user, verify they exist
let readUser = await db
.collection("Users")
.findOne({ _id: new ObjectId(_id) });
if (!readUser) {
return res.status(404).json({ error: "No user found with the given ID" });
}
// Active users cannot be activated again
if (readUser.active == true)
{
return res
.status(409)
.json({ error: "This user is already registered" });
}
// Check for users without a PIN field
if (!readUser.userPin) {
const result = await db.collection("Users").updateOne(
{ _id: new ObjectId(_id) }, // searching for a specific id syntax
{
$set: {active:true}
});
return res
.status(200)
.json({ message: "User registration successfully completed - no PIN field present" });
}
// If provided PIN is correct, try to register the user
if (userPin == readUser.userPin)
{
// Try to delete the PIN field
const result = await db.collection("Users").updateOne(
{ _id: new ObjectId(_id) }, // searching for a specific id syntax
{
$unset: {userPin:''},
$set: {active:true}
});
return res
.status(200)
.json({ message: "User registration successfully completed" });
}
// If we made it here, the PIN is incorrect
return res
.status(403)
.json({ error: "Incorrect PIN provided" });
} catch (e) {
return res.status(500).json({ error: "An internal server error occurred" });
}
});
// ANCHOR Update Password
// Codes:
// 200 (password updated)
// 400 (missing password)
// 401 (incorrect current password)
// 403 (ownership error)
// 404 (user not found)
// 500 (generic error)
app.post("/api/updatepassword/:_id", authToken, async (req, res) => {
// incoming: password
// outgoing: success or error
const { currPassword, password } = req.body;
// Verify a new password and previous password are provided
if (!password || !currPassword) {
return res.status(400).json({ error: "No password or previous password provided" });
}
try {
// Get user id and verify it is owned by the user
let _id = req.params._id;
if (_id !== req.user.userId.toString()) {
return res
.status(403)
.json({ error: "Ownership error" });
}
// Fetch the user, verify it exists
let readUser = await db
.collection("Users")
.findOne({ _id: new ObjectId(_id) });
if (!readUser) {
return res.status(404).json({ error: "User not found" });
}
// Verify the previous password is good
const checkPassword = await bcrypt.compare(currPassword, readUser.password);
if (!checkPassword) {
return res.status(401).json({ error: "Current password is incorrect" });
}
// Hash new password and update
const hashedPasswd = await bcrypt.hash(password, 10);
const updatedFields = {};
updatedFields.password = hashedPasswd;
const result = await db.collection("Users").updateOne(
{ _id: new ObjectId(_id) }, // searching for a specific id syntax
{
$set: updatedFields
}
);
return res.status(200).json({ message: "Updated password successfully" });
} catch (e) {
return res.status(500).json({ error: "Server error in creation of user" });
}
});
// ANCHOR Reset Password
// Codes:
// 200 (password updated)
// 400 (missing password)
// 401 (incorrect current password)
// 403 (ownership error)
// 404 (user not found)
// 500 (generic error)
app.post("/api/resetpassword", async (req, res) => {
// incoming: email
// outgoing: success or error
const { email } = req.body;
// Make sure email is given
if (!email ) {
return res.status(400).json({ error: "No email provided" });
}
try {
// Fetch user with email, verify is found
const existingUser = await db.collection("Users").findOne({
email: email,
});
if (!existingUser) {
return res.status(404).json({ error: "User not found" });
}
// Get key, only update if email server configured
let key = process.env.POSTMARK_KEY;
if (key != "0") {
// Generate random password
const tempPass = crypto.randomBytes(8).toString('hex');
// Update password in the database
const hashedPasswd = await bcrypt.hash(tempPass, 10);
const updatedFields = {};
updatedFields.password = hashedPasswd;
const result = await db.collection("Users").updateOne(
{ email: email }, // searching for a specific id syntax
{
$set: updatedFields
}
);
// Send email for new password
const client = new postmark.ServerClient(key);
client.sendEmailWithTemplate({
"TemplateId": 38229008,
"From": "noreply@overcastly.app",
"To": email,
"TemplateModel": { product_url: "overcastly.app", product_name:"Overcastly", company_name:"Overcastly", company_address:"Orlando, FL", name:existingUser.firstName, user_pass:tempPass}
});
}
else {
return res.status(403).json({ error: "No API key for Postmark Email Service" });
}
return res.status(200).json({ message: "Updated password successfully" });
} catch (e) {
return res.status(500).json({ error: "Server error in creation of user" });
}
});
// ANCHOR Get User
// Codes:
// 200 (user found)
// 404 (user not found)
// 500 (generic error)
app.get("/api/users/:_id", async (req, res) => {
// incoming: user Id
// outgoing: user info
try {
let _id = req.params._id;
let readUser = await db
.collection("Users")
.findOne({ _id: new ObjectId(_id) });