-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
982 lines (888 loc) · 32.1 KB
/
server.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
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
// Imports
var express = require("express");
var bodyParser = require("body-parser");
var cors = require('cors');
var path = require('path');
var _ = require('lodash');
var secure = require('ssl-express-www')
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var JwtStrategy = require('passport-jwt').Strategy;
var ExtractJwt = require('passport-jwt').ExtractJwt;
var jwt = require('jsonwebtoken');
var nodemailer = require('nodemailer');
var app = express();
// Middleware
app.use(secure);
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ limit: '10mb', extended: true, parameterLimit: 10000 }));
app.use(cors({ origin: '*' }));
app.use(cors({
origin: [
'https://comp4920-organiser.herokuapp.com',
'http://localhost:4200',
],
}));
// Create link to Angular build directory
var distDir = __dirname + "/dist/";
app.use(express.static(distDir));
// Create a database variable outside of the database connection callback to reuse the connection pool in your app.
var db;
// Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI || "mongodb://heroku_5x9x11zk:[email protected]:45772/heroku_5x9x11zk", function (err, client) {
if (err) {
console.log(err);
process.exit(1);
}
// Save database object from the callback for reuse.
db = client.db();
console.log("Database connection ready");
// Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
// error handler
function returnError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({ "error": message });
}
// Passport middleware configuration
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(username, password, done){
return db.collection(USERS_COLLECTION).findOne({email, password}, function(err, user){
if (err){
return done(err, false, {success: false, message : 'Wrong email or password'});
} if (user){
return done(null, user, {success: true});
} else {
return done(null, false, {success: false, message: 'Must provide email and password'});
}
});
}
))
var opts = {};
opts.jwtFromRequest = ExtractJwt.fromAuthHeaderAsBearerToken();
opts.secretOrKey = 'Johnson4920';
passport.use( new JwtStrategy(opts, function(jwt_payload, done){
return db.collection(USERS_COLLECTION).findOne({ _id : ObjectID(jwt_payload._id)}, function(err, user){
if (err){
return done(err, false);
} if (user){
return done(null, user);
} else {
return done(null, false);
}
});
}));
/**
******************************** USERS ********************************
*/
var USERS_COLLECTION = 'USERS';
// Authenticate user
app.post('/api/auth', function(req, res) {
if (req.body.email && req.body.password) { // Field Check
db.collection(USERS_COLLECTION).findOne({ email: req.body.email }, function (err, result) {
if (result) {
if (req.body.password == result.password) {
var unsigned_token = result;
unsigned_token.profile = "";
unsigned_token.password = "";
var token = jwt.sign(unsigned_token, 'Johnson4920');
res.status(200).json({ success: true, token: token});
} else {
res.json({ success: false });
}
} else {
res.status(200).json({success: false});
}
});
} else {
returnError(res, 'Invalid user input', 'Must provide email and password', 400);
}
});
// Create user
app.put('/api/register', function(req, res) {
if(req.body.email && req.body.password) {
var obj = req.body;
console.log ("RECEIVED OBJECT:");
console.log (obj);
db.collection(USERS_COLLECTION).findOne({email : req.body.email}, function(err, result){
if(result){ // Existing user with same email found
res.status(200).json({success: false, message: "email has been used in another account"});
} else{
db.collection(USERS_COLLECTION).insertOne(obj, function (err, result) {
if (err) res.status(200).json({success: false, message: "database error"}); //DB Error
else {
const token = jwt.sign(obj, 'Johnson4920');
res.status(201).json({success: true, token});
}
});
}
});
} else res.status(400).json({success: false, message: "Must provide email and password"});
});
// Get all users (with auth)
app.get('/api/users', passport.authenticate('jwt', {session: false}), function (req, res) {
db.collection(USERS_COLLECTION).find({}, {_id:1}).toArray(function (err, result) {
if (result) {
res.status(200).json(result);
} else {
returnError(res, err.message, "Failed to retrieve users");
}
});
});
// Get current user (with auth)
app.get('/api/me', passport.authenticate('jwt', {session: false}), function (req, res) {
res.status(200).json({"currUser": req.user._id});
});
//Get user data by user id param
app.get('/api/account/data/:id', passport.authenticate('jwt', {session: false}), function(req, res){
db.collection(USERS_COLLECTION).findOne({_id: ObjectID(req.params.id)}, function(err, doc){
if(doc == null || err){
returnError(res, "User not Found", "User not Found", 400);
} else {
res.status(200).json(doc);
}
})
})
//change user data by token ID
app.put('/api/account/data', passport.authenticate('jwt', {session: false}), function(req, res){
db.collection(USERS_COLLECTION).updateOne({_id: ObjectID(req.user._id)}, {$set : req.body}, function(err, doc){
if(doc == null || err){
returnError(res, "User not Found", "User not Found", 400);
} else {
res.status(200).json({success:true});
}
})
})
//Check user if exists by email
app.get('/api/account/check/:email', function(req, res) {
db.collection(USERS_COLLECTION).findOne({email : req.params.email}, function(err, doc) {
if(doc == null){
returnError(res, "Account not Found", "Account not Found", 400);
} else {
res.status(200).json({success : true});
}
});
});
//Change user data by email param
app.put('/api/account/change/:email', function(req, res) {
db.collection(USERS_COLLECTION).updateOne({email: req.params.email}, { $set: req.body }, function (err, doc){
if (err){
returnError(res, err, "Cannot update credential", 400);
} else {
res.json({success : true});
}
})
});
//Get account data by token ID
app.get('/api/account/data', passport.authenticate('jwt', {session: false}), function(req, res){
db.collection(USERS_COLLECTION).findOne({_id: ObjectID(req.user._id)}, function(err, doc){
if(doc == null || err){
returnError(res, "User not Found", "User not Found", 400);
} else {
res.status(200).json(doc);
}
})
})
//Send email verification, returns verification code
app.post('/api/account/email_verification', function(req, res){
db.collection(USERS_COLLECTION).findOne({email : req.body.email}, function(err, doc){
if(err){
returnError(res, "Account not Found", "Account Not Found", 400);
} else{
let transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'Johnson4920'
}
});
var randomCode = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15); //https://gist.github.com/6174/6062387
randomCode = randomCode.substring(0,10);
let mailOptions = {
from: '[email protected]',
to: req.body.email,
subject: 'Password Change Request',
text: randomCode
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
returnError(res, "Error occured when sending email", "Error occured when sending email", 400);
} else {
console.log('Email sent: ' + info.response); //DEBUG
res.status(200).json({success: true, code: randomCode});
}
});
}
})
});
/**
* ************************ LISTS ************************
*/
let LISTS_COLLECTION = 'LISTS';
// Create list
app.post('/api/list', passport.authenticate('jwt', {session: false}), function (req, res) {
var newList = req.body;
newList.createdAt = new Date();
newList.createdBy = req.user._id;
if (!req.body.title) {
returnError(res, 'Invalid user input', 'Must provide a title', 400);
} else {
db.collection(LISTS_COLLECTION).insertOne(newList, function (err, doc) {
if (err) {
returnError(res, err.message, "Failed to create new list");
} else {
res.status(201).json(doc.ops[0]);
}
});
}
});
// Get all lists a user is a part of (created or added as a collaborator)
app.get('/api/list' , passport.authenticate('jwt', { session: false }), function (req, res) {
db.collection(LISTS_COLLECTION)
.find({
$and: [
{
// Team lists are not included
"teamID" : { "$exists" : false }
},
{
$or: [
{ createdBy: req.user._id },
{ collaborators: { $in: [ req.user._id ] } },
]
}
]
})
.sort({ important: -1, createdAt: 1 })
.toArray(function (err, docs) {
if (err) {
returnError(res, err.message, "Failed to retieve lists");
} else {
res.status(200).json(docs);
}
});
});
// Get a list with specific id
app.get('/api/list/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(LISTS_COLLECTION).findOne({ _id: ObjectID(req.params.id) }, function (err, list) {
if (err) {
returnError(res, err.message, "Failed to retieve list");
} else {
if (list) {
if (list.collaborators && list.collaborators.length > 0) {
db.collection(USERS_COLLECTION)
.find({ _id: { $in: [...list.collaborators, list.createdBy].map(user => ObjectID(user)) } })
.toArray(function (err, users) {
const listWithUsers = { ...list };
listWithUsers.createdBy = users.find(user => ObjectID(list.createdBy).equals(user._id) );
listWithUsers.collaborators = list.collaborators.map(collaborator =>
users.find(user => ObjectID(collaborator).equals(user._id))
);
res.status(200).json(listWithUsers);
});
} else {
res.status(200).json(list);
}
} else {
returnError(res, 'No list found', 'No list found', 404);
}
}
});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
// Delete list with specific id
app.delete('/api/list/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(LISTS_COLLECTION).deleteOne({ _id: ObjectID(req.params.id) }, function (err, doc) {
if (err) {
returnError(res, err.message, "Failed to delete list");
} else {
if (doc.deletedCount > 0) {
res.status(200).json({"message": "success"});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
}
});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
// Update a list
app.put('/api/list/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(LISTS_COLLECTION).updateOne({ _id: ObjectID(req.params.id)}, { $set: req.body }, function (err, result) {
if (err) {
returnError(res, err.message, "Failed to update list");
} else if (result.result.n === 1) {
res.status(204).send({});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
// Add a user to a list
app.post('/api/list/:id/collaborators/:userId', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(LISTS_COLLECTION).updateOne({
_id: ObjectID(req.params.id)},
{ $push: { collaborators: req.params.userId } },
function (err, result) {
if (err) {
returnError(res, err.message, "Failed to update list");
} else if (result.result.n === 1) {
res.status(204).send({});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
// Remove a user from a list
app.delete('/api/list/:id/collaborators/:userId', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(LISTS_COLLECTION).updateOne({
_id: ObjectID(req.params.id)},
{ $pull: { collaborators: req.params.userId } },
function (err, result) {
if (err) {
returnError(res, err.message, "Failed to update list");
} else if (result.result.n === 1) {
res.status(204).send({});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
} else {
returnError(res, 'No list found', 'No list found', 404);
}
});
/**
* ******************************** TASKS ********************************
*/
var TASKS_COLLECTION = 'TASKS';
// Create task
app.post('/api/task', passport.authenticate('jwt', { session: false }), function (req, res) {
const newTask = req.body;
const now = new Date();
newTask.createdAt = now;
newTask.orderDate = now;
newTask.createdBy = ObjectID(req.user._id);
if (newTask.listId) {
newTask.listId = ObjectID(newTask.listId);
}
if (!req.body.title) {
returnError(res, 'Invalid user input', 'Must provide a title', 400);
} else {
db.collection(TASKS_COLLECTION).insertOne(newTask, function (err, doc) {
if (err) {
returnError(res, err.message, "Failed to create new task");
} else {
res.status(201).json(doc.ops[0]);
}
});
}
});
// Get all tasks owned by the user
app.get('/api/task', passport.authenticate('jwt', { session: false }), function (req, res) {
const filterParams = {
completed: { $in: [null, false] },
deleted: { $in: [null, false] },
};
if (req.query.teamId) {
filterParams.teamId = req.query.teamID
} else {
filterParams.createdBy = ObjectID(req.user._id);
}
if (req.query.completed === 'true') {
filterParams.completed = true;
}
if (req.query.deleted === 'true') {
filterParams.deleted = true;
}
if (req.query.listId && ['today', 'me', 'upcoming'].indexOf(req.query.listId) === -1) {
filterParams.listId = ObjectID(req.query.listId);
}
if (req.query.listId && req.query.listId === 'upcoming') {
filterParams.$or = [
{ assignee: ObjectID(req.user._id) },
{ createdBy: ObjectID(req.user._id) },
];
filterParams.dueDate = { $exists: true };
}
if (req.query.listId && req.query.listId === 'me') {
filterParams.assignee = ObjectID(req.user._id);
} else {
if (req.query.teamId) {
filterParams.teamId = req.query.teamID
} else {
filterParams.createdBy = ObjectID(req.user._id);
}
}
db.collection(TASKS_COLLECTION)
.find(filterParams)
.sort({ important: -1, orderDate: -1 })
.toArray(function (err, tasks) {
if (err) {
returnError(res, err.message, "Failed to retieve tasks");
} else {
const assignees = tasks.map(task => ObjectID(task.assignee)).filter(val => val);
db.collection(USERS_COLLECTION).find({ _id: { $in: assignees } })
.toArray((err, users) => {
let finalTasks = tasks.map(task => {
task.assignee = users.find(user => ObjectID(task.assignee).equals(user._id));
return task;
});
const listIds = tasks.map(task => ObjectID(task.listId)).filter(val => val);
db.collection(LISTS_COLLECTION)
.find({ _id: { $in: listIds } })
.project({ teamID: 1, title: 1 })
.toArray((err, lists) => {
const teamIds = lists.map(list => ObjectID(list.teamID)).filter(val => val);
db.collection(TEAMS_COLLECTION)
.find({ _id: { $in: teamIds } })
.project({ name: 1 })
.toArray((err, teams) => {
finalLists = lists.map(list => {
if (list.teamID) {
list.team = teams.find(team => ObjectID(list.teamID).equals(team._id));
}
return list;
});
finalTasks = tasks.map(task => {
task.list = finalLists.find(list => ObjectID(task.listId).equals(list._id));
return task;
});
res.status(200).json(finalTasks);
});
});
});
}
});
});
// Get task with specific id
app.get('/api/task/:id', passport.authenticate('jwt', { session: false }), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(TASKS_COLLECTION).findOne({ _id: ObjectID(req.params.id) }, function (err, doc) {
if (err) {
returnError(res, err.message, "Failed to retieve task");
} else {
if (doc) {
res.status(200).json(doc);
} else {
returnError(res, 'No task found', 'No task found', 404);
}
}
});
} else {
returnError(res, 'Invalid user input', 'Invalid task ID', 400);
}
});
// Update task with specific id
app.put('/api/task/:id', passport.authenticate('jwt', { session: false }), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
const updatedTask = { ...req.body };
if (req.body.orderDate) {
updatedTask.orderDate = new Date(Date.parse(req.body.orderDate));
}
if (req.body.listId) {
updatedTask.listId = ObjectID(req.body.listId);
}
if (req.body.assignee) {
updatedTask.assignee = ObjectID(req.body.assignee);
}
db.collection(TASKS_COLLECTION).updateOne({ _id: ObjectID(req.params.id) }, { $set: updatedTask }, function (err, result) {
if (err) {
returnError(res, err.message, "Failed to update task");
} else if (result.result.n === 1) {
res.status(204).send({});
} else {
returnError(res, 'No task found', 'No task found', 404);
}
})
} else {
returnError(res, 'Invalid user input', 'Invalid task ID', 400);
}
});
/**
* **************************** TEAMS WITH AUTH ****************************
*/
let TEAMS_COLLECTION = 'TEAMS';
// Create team
app.post('/api/team', passport.authenticate('jwt', {session: false}), function (req, res) {
var newTeam = req.body;
newTeam.createdAt = new Date();
newTeam.createdBy = req.user._id;
newTeam.leaders = [];
newTeam.leaders.push(req.user._id);
if(newTeam.members) {
// Non empty team initialisation
newTeam.members = newTeam.members.map((member) => {
if (member.isLeader) {
newTeam.leaders.push(ObjectID(member.user._id));
}
return ObjectID(member.user._id);
});
}
var newList = {
"title" : "Default List",
"createdAt" : new Date(),
"createdBy" : req.user._id
};
db.collection(TEAMS_COLLECTION).insertOne(newTeam, function (err1, doc1) {
if (err1) {
returnError(res, err1.message, "Failed to create new team");
} else {
// Team created. Now create the default list
newList.teamID = doc1.ops[0]._id;
db.collection(LISTS_COLLECTION).insertOne(newList, function (err2, doc2) {
if (err2) {
returnError(res, err2.message, "Failed to create default list for new team");
} else {
res.status(201).json(doc1.ops[0]);
}
});
}
});
});
// Get all teams a user is in
app.get('/api/team' , passport.authenticate('jwt', { session: false }), function (req, res) {
db.collection(TEAMS_COLLECTION)
.find({
$or: [
{ members: { $in: [ req.user._id, `${req.user._id}` ] } },
{ createdBy: { $in : [ req.user._id, `${req.user._id}` ] } },
],
})
.toArray((err, teams) => {
if (err) {
returnError(res, err.message, "Failed to retieve teams");
} else {
res.status(200).json(teams);
}
});
});
// Get team with specific id
app.get('/api/team/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
db.collection(TEAMS_COLLECTION).findOne({ _id: ObjectID(req.params.id) }, function (err, team) {
if (err) {
returnError(res, err.message, "Failed to retieve teams");
} else {
if (team) {
let teamMembers = team.members;
let users = _.uniq(_.concat(team.createdBy, teamMembers));
db.collection(USERS_COLLECTION)
.find({ _id: { $in: users.map(user => ObjectID(user)) } })
.toArray((err, users) => {
team.creator = {
user: users.find(user => ObjectID(team.createdBy).equals(user._id)),
isCreator: true,
isLeader: true,
};
if (team.members) {
team.members = team.members.map(memberId => ({
user: users.find(user => ObjectID(memberId).equals(user._id)),
isCreator: false,
isLeader: !!team.leaders.find(leader => ObjectID(memberId).equals(leader)),
}));
}
res.status(200).json(team);
});
} else {
returnError(res, 'No team found', 'No team found', 404);
}
}
});
} else {
returnError(res, 'Invalid user input', 'Invalid team ID', 400);
}
});
// Delete team with specific id
app.delete('/api/team/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
// Check if the team is valid
db.collection(TEAMS_COLLECTION).deleteOne({ _id: ObjectID(req.params.id) }, function (err, doc) {
if (err) {
returnError(res, err.message, "Failed to delete team");
} else {
if(doc.deletedCount > 0) {
res.status(200).json({"message": "success"});
} else {
returnError(res, 'No team found', 'No team found', 404);
}
}
});
} else {
returnError(res, 'Invalid user input', 'Invalid team ID', 400);
}
});
// Update a team
app.put('/api/team/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
if (ObjectID.isValid(req.params.id)) {
// Only description, banner and name can be updated
if(req.body.banner) {
// Has banner
var toUse = {
"banner": req.body.banner,
"description": req.body.description,
"name": req.body.name
};
} else {
// No banner
var toUse = {
"description": req.body.description,
"name": req.body.name
};
}
db.collection(TEAMS_COLLECTION).updateOne({ _id: ObjectID(req.params.id)}, { $set: toUse }, function (err, result) {
if (err) {
returnError(res, err.message, "Failed to update teams");
} else if (result.result.n === 1) {
res.status(204).send({});
} else {
returnError(res, 'No team found', 'No team found', 404);
}
});
} else {
returnError(res, 'Invalid user input', 'Invalid team ID', 400);
}
});
// Add the current user, or a specific user to a team
app.put('/api/team/:id/member', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
if("_id" in req.body) {
db.collection(TEAMS_COLLECTION).updateOne(
{ _id: ObjectID(req.params.id) },
{ $push: { members: ObjectID(req.body._id) } },
(err, doc) => {
if (err){
returnError(res, err.message, "Failed to add member");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
db.collection(TEAMS_COLLECTION).updateOne(
{ _id: ObjectID(req.params.id) },
{ $push: { members: ObjectID(req.user._id) } },
(err, doc) => {
if (err){
returnError(res, err.message, "Failed to add member");
} else{
res.status(200).json({ "message": "success" });
}
});
}
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Remove the current user, or a specific member from a team
app.delete('/api/team/:id/member', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
if("_id" in req.body) {
db.collection(TEAMS_COLLECTION)
.updateOne(
{ _id : ObjectID(req.params.id) },
{ $pull: { members: ObjectID(req.body._id) } },
(err, doc) => {
if (err){
returnError(res, err.message, "Failed to delete member");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
db.collection(TEAMS_COLLECTION).updateOne(
{ _id: ObjectID(req.params.id)},
{ $pull: { members: ObjectID(req.user._id) } },
(err, doc) => {
if (err){
returnError(res, err.message, "Failed to delete member");
} else{
res.status(200).json({ "message": "success" });
}
});
}
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Add the current user, or a specific user to a team
app.put('/api/team/:id/leader/:userId', passport.authenticate('jwt', { session: false }), function(req, res){
if (ObjectID.isValid(req.params.userId)) {
db.collection(TEAMS_COLLECTION)
.updateOne(
{ _id: ObjectID(req.params.id)},
{ $push: { leaders: ObjectID(req.params.userId) } },
(err, doc) => {
if (err){
returnError(res, err.message, "Failed to add member");
} else {
res.status(200).json({ "message": "success" });
}
});
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Remove the current user, or a specific member from a team
app.delete('/api/team/:id/leader/:userId', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
db.collection(TEAMS_COLLECTION)
.updateOne(
{ _id: ObjectID(req.params.id) },
{ $pull: { leaders: ObjectID(req.params.userId) } },
(err, doc) => {
if (err){
returnError(res, err.message, "Failed to delete member");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Add a list to a team
app.put('/api/team/:id/list', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
db.collection(TEAMS_COLLECTION).updateOne({_id : ObjectID(req.params.id)}, {$push :{lists : ObjectID(req.body._id)}}, function(err, doc){
if (err){
returnError(res, err.message, "Failed to add list");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Get all lists for a team
app.get('/api/team/:id/lists' , passport.authenticate('jwt', { session: false }), function (req, res) {
db.collection(LISTS_COLLECTION)
.find({ "teamID" : req.params.id })
.sort({ important: -1, createdAt: 1 })
.toArray(function (err, docs) {
if (err) {
returnError(res, err.message, "Failed to retieve lists");
} else {
res.status(200).json(docs);
}
});
});
// Remove a list from a team
app.delete('/api/team/:id/list', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
db.collection(TEAMS_COLLECTION).updateOne({_id : ObjectID(req.params.id)}, {$pull :{lists : ObjectID(req.body._id)}}, function(err, doc){
if (err){
returnError(res, err.message, "Failed to delete list");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Set a team member as a leader
app.put('/api/team/:id/leader', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
db.collection(TEAMS_COLLECTION).updateOne({_id : ObjectID(req.params.id)}, {$push :{leaders : req.body._id}}, function(err, doc){
if (err){
returnError(res, err.message, "Failed to add leader");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
// Remove leader status from a team leader
app.delete('/api/team/:id/leader', passport.authenticate('jwt', {session: false}), function(req, res){
if (ObjectID.isValid(req.params.id)) {
db.collection(TEAMS_COLLECTION).updateOne({_id : ObjectID(req.params.id)}, {$pull :{leaders : req.body._id}}, function(err, doc){
if (err){
returnError(res, err.message, "Failed to delete leader");
} else{
res.status(200).json({ "message": "success" });
}
});
} else {
returnError(res, 'Incorrect team ID format', 'Incorrect team ID format', 404);
}
});
/**
* ******************************** MESSAGES ********************************
*/
let MESSAGES_COLLECTION = 'MESSAGES';
// Create a new message
app.post('/api/messages/team/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
var newMessage = req.body;
newMessage.createdAt = new Date();
newMessage.createdBy = req.user._id;
newMessage.teamID = ObjectID(req.params.id);
db.collection(MESSAGES_COLLECTION).insertOne(newMessage, function (err, doc) {
if (err) {
returnError(res, err.message, "Failed to create new message");
} else {
res.status(201).json(doc.ops[0]);
}
});
});
// Get all messages for a team
app.get('/api/messages/team/:id', passport.authenticate('jwt', {session: false}), function (req, res) {
db.collection(MESSAGES_COLLECTION)
.find({ "teamID" : ObjectID(req.params.id) })
.sort({ createdAt: -1 })
.toArray(function (err, messages) {
if (err) {
returnError(res, err.message, "Failed to retieve messages");
} else {
const userIds = _.uniq(messages.map(message => ObjectID(message.createdBy)));
db.collection(USERS_COLLECTION).find({ _id: { $in: userIds } }).toArray((err, users) => {
let finalMessages = messages.map((message) => {
message.createdBy = users.find(user => ObjectID(message.createdBy).equals(user._id));
return message;
});
res.status(200).json(finalMessages);
});
}
});
});
// Delete a message
app.delete('/api/messages/:mid', passport.authenticate('jwt', {session: false}), function (req, res) {
db.collection(MESSAGES_COLLECTION).deleteOne({_id : ObjectID(req.params.mid)}, function(err, doc){
if (err){
returnError(res, err.message, "Failed to delete message");
} else {
res.status(200).json({ "message": "success" });
}
});
});
/**
* ************************ OTHER ************************
*/
// Catchall route to always serve angular app
app.get('*', (req, res) => {
res.sendFile(path.join(distDir, '/index.html'));
});