-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
1820 lines (1601 loc) Β· 53.1 KB
/
app.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
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const express = require('express') // Express as a Webserver
, path = require('path') // path used for local file access
, favicon = require('serve-favicon') // Serve favicons for every request
, logger = require('morgan') // Morgan to log requests to the console
, cookieParser = require('cookie-parser') // Cookie parser to, well, parse cookies
, bodyParser = require('body-parser') // Again, the name stands for the concept, parse HTTP POST bodies
, mongoose = require('bluebird').promisifyAll(require('mongoose')) // Mongoose is used to connect to the mongoDB server
, methodOverride = require('method-override') // Method Override to use delete method for elemets
, i18n = require('i18n') // i18n for translations (German/English)
, session = require('client-sessions') // Client-Sessions to be able to access the session variables
, bCrypt = require('bcryptjs') // bCrypt for secure Password hashing (on the server side)
, app = express()
, mg = require('mailgun-js') // Mailgun for handling emails
, request = require("request") // request for reCaptcha validation
, fs = require("fs")
, jwt = require("jsonwebtoken") // jwt as a means of authentication
, cloudinary = require("cloudinary")
, config = require("./config.js") // config file
, ObjectID = mongoose.Schema.Types.ObjectId
;
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.disable('x-powered-by');
app.use(favicon(path.join(__dirname, 'public', "static" , 'images', 'favicon.png')));
app.use(logger('short'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(methodOverride());
const mailgun = mg({apiKey: config.mailgun.privateKey, domain: config.mailgun.domain});
i18n.configure({
//define what languages we support in our application
locales: ['en', 'de'],
//define the path to language json files, default is /locales
directory: __dirname + '/locales',
//define the default language
defaultLocale: 'en',
// define a custom cookie name to parse locale settings from
cookie: 'preferredLang',
// sync locale information across files
syncFiles: false,
updateFiles: false
});
app.use(cookieParser("preferredLang"));
app.use(session({
secret: "preferredLang",
resave: true,
saveUninitialized: true,
cookie: {maxAge: 900000, httpOnly: true}
}));
app.use(i18n.init);
console.info("ListX Started on http://" + config.domain);
// database setup
mongoose.Promise = Promise;
mongoose.connect('mongodb://' + config.mongo.address) // sudo mongod --dbpath=/var/data --port=27070 --fork --logpath=./log.txt
.then(
() => { console.info("Connected to mongoDB.") },
err => { console.log("Connection to mongoDB failed: "+err) }
);
cloudinary.config(config.cloudinary);
const Item = mongoose.model('Item', {
list: ObjectID,
name: String,
amount: String,
count: Number,
art: String,
date: {
type: Date,
default: Date.now
},
remember: Boolean,
bought: {type: Boolean, default: false},
image: String,
image_id: String
});
const User = mongoose.model('User', {
username: String,
name: String,
email: String,
password: String,
lists: [], // 1 User => 0+ Lists
premium: {type: Boolean, default: false},
alphaTester: {type: Boolean, default: false},
betaTester: {type: Boolean, default: false},
validated: {type: Boolean, default: false},
address: String,
zipCode: String,
country: String,
additionalFields: [],
date: {
type: Date,
default: Date.now
}
});
const EmailValidation = mongoose.model("EmailValidation", {
email: String,
userId: ObjectID,
expiry: {
type: String, default: () => {
return (new Date(Date.now() + 45 * 60 * 1000)).getTime().toString();
}
} // 45 Minutes
});
const PasswordReset = mongoose.model("PasswordReset", {
userId: ObjectID,
expiry: {
type: String, default: () => {
return (new Date(Date.now() + 45 * 60 * 1000)).getTime().toString();
}
} // 45 Minutes
});
const UserDeletionToken = mongoose.model("UserDeletionToken", {
userId: ObjectID
});
const EmailReset = mongoose.model("EmailReset", {
userId: ObjectID,
expiry: {
type: String, default: () => {
return (new Date(Date.now() + 45 * 60 * 1000)).getTime().toString();
}
} // 45 Minutes
});
const List = mongoose.model('List', {
name: String,
country: String,
language: String,
admin: ObjectID,
invitations: [], // 1 List => 0+ Open Invitations
date: {
type: Date,
default: Date.now
}
});
const Invitation = mongoose.model('Invitation', {
name: String,
email: String,
list: ObjectID
});
const ShortDomain = mongoose.model('ShortDomain', {
short: String,
long: String,
hits: {type: Number, default: 0}
});
app.get("/api/short/:short", (req, res) => {
const {short} = req.params;
const long = req.query.long;
linkShortener(long, short, obj => res.json(obj));
});
app.get("/api/short/:short/metrics", (req, res) => {
ShortDomain.findOne({short: req.params.short}, (err, url) => {
if (!err && url) res.json(url);
});
});
app.get("/s/:short", (req, res) => {
// increment the hits-counter by one and redirect to LONG
ShortDomain.findOneAndUpdate({short: req.params.short}, {$inc: {hits: 1}}, (err, url) => {
if (err) res.redirect("/");
res.redirect(url.long);
});
});
/**
* UI CONTROLLER
*/
app.post('/signup', (req, res) => {
validateReCAPTCHA(req.body["g-recaptcha-response"], (err, success) => {
if (success) {
bCrypt.genSalt(10, (err, salt) => {
bCrypt.hash(req.body.password, salt, function (err, hash) {
let userData = {
name: req.body.name,
email: req.body.email,
password: hash
};
if (req.body.list) userData.lists = [req.body.list];
User.create(userData, function (err, user) {
if (err) {
res.json({success: false});
}
EmailValidation.create({email: user.email, userId: user._id}, (err, valid) => {
if (err) res.json({success: false});
const short = "http://" + config.domain + "/validate/" + valid._id;
let mailData = {};
mailData.to = user.email;
mailData.subject = "ListX Account Activation";
mailData.body = `ListX Account Activation \nHey ${req.body.name}, thanks for signing up with ListX! \nPlease verify your email address by clicking the following link: \n${short} (Voids in 45 minutes)\nSee you on the other side!`;
mailData.send = true;
mail(mailData)
.then(msg => {
console.log("Signup Proccess complete: ", msg);
res.json({success: true, user: user, validation: valid});
})
.catch(err => {
console.error("Singup Proccess not completed", err);
});
});
});
});
});
} else {
res.json({success: false, error: err, code: 701});
}
});
});
// signup page for users
app.get('/signup', function (req, res) {
if (req.query.p === "β") { /** premium signup **/
}
if (req.query.b === "β") { /** beta signup **/
}
res.render('signup', {
email: "",
list: null
});
});
/**
* EMail Validation: Get Validation ID, find Email, see if not expired, set user.validation = true, delete EmailValidation, send success mail, redirect to dashboard
*/
app.get("/validate/:id", function (req, res) {
EmailValidation.findOne({_id: req.params.id}, (err, valid) => {
if (err) res.json({success: false});
if (Number(valid.expiry) >= new Date(Date.now()).getTime()) {
// Validation not expired
User.findOneAndUpdate({_id: valid.userId}, {$set: {validated: true}}, (err, u) => {
// if there was an error, redirect to /signup and pass error 201 (user not found)
if (err) res.redirect("/signup?e=201");
// else redirect to login
res.redirect("/login");
});
}
else {
// if validation expired, delete account and send to signup with error 601 (validation expired)
User.findOneAndRemove({_id: valid.userId}, (err) => {
console.log(err)
});
res.redirect("/signup?e=601")
}
})
});
/**
* Password Reset: Only display Email input
*/
app.get("/user/reset-password", (req, res) => {
if (req.query.expired === "1") {
// Password link expired.
res.render("reset-password-email-form", {expired: true});
}
res.render("reset-password-email-form", {expired: false});
});
/**
* Get Email from body, send mail to email,
* if mail is user: send password reset link
* else: send bruteforce reminder
*/
app.post("/api/reset", (req, res) => {
const email = req.body.email;
validateReCAPTCHA(req.body.recRes, (err, success) => {
if (success) {
User.findOne({email: email}, function (err, user) {
if (err || !user) {
let mailData = {
to: email,
subject: "ListX Password Reset Attempt",
body: `You (or someone else) just entered this email address (${email}) when trying to change the password of a ListX account. \n\nHowever there is no user with this email address in our database, thus the password reset attempt failed. \n\nIf you are in fact a ListX customer and were expecting this email, please try again using the email address you gave when opening your account. \n\nIf you are not a ListX customer ignore this email. Someone most likely mistyped his own email address. \n\nFor more information on ListX, please visit http://listx.io. \n\nListX Support`,
send: true
};
mail(mailData)
.then(msg => res.json({success: true}))
.catch(err => res.json({success: false, error: err}));
} else {
PasswordReset.create({userId: user._id}, (err, pwr) => {
let long = "http://" + config.domain + "/user/reset-password/" + pwr._id;
linkShortener(long, null, URL => {
URL = "http://" + config.domain + "/s/" + URL.short;
let mailData = {
to: user.email,
subject: "ListX Password Reset",
body: `Hey ${user.name}, \nYou (or someone else) just entered this email address (${user.email}) when trying to change the password of a ListX account. \n\nIf it was you and you are trying to reset or change your password, please follow this link in order to set a new password: \n${URL} (Voids in 45 minutes)\n\nIf you did not request a password reset or change, please ignore this email. Someone most likely mistyped his own email address. \n\nListX Support`,
send: true
};
mail(mailData)
.then(msg => res.json({success: true}))
.catch(err => res.json({success: false, error: err}));
});
});
}
});
} else {
res.json({success: false, error: err})
}
});
});
/**
* Password reset link: display password form
*/
app.get("/user/reset-password/:id", (req, res) => {
PasswordReset.findOne({_id: req.params.id}, (err, pwr) => {
if (err) res.json({success: false});
console.log(pwr.expiry, Date.now());
if (pwr.expiry >= Date.now()) {
res.render("reset-password-password-form", {
userId: pwr.userId,
pwrId: req.params.id
});
}
else {
res.redirect("/user/reset-password?expired=1");
}
});
});
app.post("/api/passwordreset", (req, res) => {
let {pwrId, password} = req.body;
bCrypt.hash(password, 10, function (err, hashedpassword) {
PasswordReset.findOneAndRemove({_id: pwrId}, (err, pwr) => {
if (err) res.json({success: false, code: 101});
User.findOneAndUpdate({_id: pwr.userId}, {$set: {password: hashedpassword}}, (err, user) => {
if (err) res.json({success: false, error: 201});
console.log("Passwordreset for: ", user.email);
res.json({success: true});
});
});
});
});
app.post('/login', function (req, res) {
User.findOne({email: req.body.email}, function (err, user) {
console.log(user);
if (!user) {
console.error("No User with Email \"" + req.body.email + "\" found.");
res.json({correct: false});
}
else if (false === user.validated) {
console.error("User not yet validated");
res.json({correct: false, error: "User not validated", code: 602});
}
else {
bCrypt.compare(req.body.password, user.password, function (err, bc) {
if (bc) {
// sets a cookie with the user's id
res.cookie('token', jwt.sign({id: user._id}, config.jwtSecret, {expiresIn: "90d"}), {});
//req.cookies.token = jwt.sign({id:user._id}, config.jwtSecret, {expiresIn:"90d"});
console.info("User " + user.email + " successfully logged in!");
res.json({correct: true, user: user});
} else {
console.error("Wrong Password for " + user.name);
res.json({correct: false});
}
});
}
});
});
app.get('/login', (req, res) => {
verifyJWT(req.cookies.token, (err, userId) => {
if (userId) {
User.findOne({_id: userId}, (err, user) => {
if (user) res.redirect("/dashboard")
});
} else {
res.render("login");
}
});
});
app.get('/logout', (req, res) => {
res.cookie("token", "", {maxAge: new Date(0), domain: config.domain, path: "/"});
res.clearCookie("token");
res.render("logout", {domain: config.domain});
});
app.get("/auth/logout", (req, res) => {
res.cookie("token", "", {maxAge: new Date(0), domain: config.domain, path: "../"});
res.clearCookie("token");
res.render("logout", {domain: config.domain});
});
/**
* Nav Element Routes
*/
// Developer Page
app.get("/dev", (req, res) => {
res.render("index-dev");
});
app.get("/imprint", (req, res) => {
res.redirect("/legal/imprint");
});
app.get("/guides", (req, res) => {
res.render("guides");
});
app.get("/privacy", (req, res) => {
res.redirect("/legal/privacy");
});
app.get("/terms", (req, res) => {
res.redirect("/legal/terms")
});
app.get("/legal/imprint", (req, res) => {
verifyJWT(req.cookies.token, (err, userId) => {
User.findOne({_id: userId}, (err, user) => {
res.render("imprint", {user: user || false});
});
});
});
app.get("/legal/privacy", (req, res) => {
verifyJWT(req.cookies.token, (err, userId) => {
User.findOne({_id: userId}, (err, user) => {
res.render("privacy", {user: user || false});
});
});
});
app.get("/legal/terms", (req, res) => {
verifyJWT(req.cookies.token, (err, userId) => {
User.findOne({_id: userId}, (err, user) => {
res.render("terms", {user: user || false});
});
});
});
app.get("/legal/passwords", (req, res) => {
const lang = req.cookies.preferredLang;
let url = "http://blog.luca-kiebel.de/listx-passwords-";
url += lang || "en";
res.redirect(url);
});
app.get("/api/version", (req, res) => {
res.json(
{
"info": "ListX API Version Manager. Copyright 2017 Bleurque, Inc.",
"date": new Date(Date.now()).toDateString(),
"version": require("./package.json").version
}
);
});
app.get("/api/stats", (req, res) => {
let statData = [];
statData.push(User.count({}));
statData.push(User.findOne().sort({created_at: 1}).exec());
statData.push(List.count({}));
statData.push(List.findOne().sort({created_at: 1}).exec());
statData.push(Item.count({}));
statData.push(Item.findOne().sort({created_at: 1}).exec());
Promise.all(statData)
.then((stats) => {
console.log(stats);
console.log(stats[1].date);
let displayStats = {
"info": "ListX API Version Manager. Copyright 2017 Bleurque, Inc.",
"date": new Date(Date.now()).toDateString(),
"version": require("./package.json").version,
"stats": [
{
"set": "Users",
"count": stats[0],
"latestAt": new Date(stats[1].date).getTime()
},
{
"set": "Lists",
"count": stats[2],
"latestAt": new Date(stats[3].date).getTime()
},
{
"set": "Items",
"count": stats[4],
"latestAt": new Date(stats[5].date).getTime()
}
]
};
res.json(displayStats);
});
});
// https://listx.io/api/stats/usercount
app.get("/api/stats/usercount", (req, res) => {
User.count({}).then(userCount => {
res.json({
"usercount": userCount
});
});
});
app.get("/lists", (req, res) => {
res.redirect("/dashboard");
});
/**
* Stuff which needs authentication
*/
// List index per List if $user is part of it
app.get('/list/:id', requireLogin, (req, res) => {
List.findOne({_id: req.params.id}, (err, list) => {
if (err) {
res.render('index', {error: 'List not found!'});
}
verifyJWT(req.cookies.token, (err, userId) => {
if (userId) {
User.findOne({_id: userId}, (err, user) => {
if (user.lists.indexOf(list._id) >= 0) {
res.render('list', {
list: list, user: user
});
}
else {
console.log("User " + user.name + " is not member of List " + list.name);
res.render('index', {error: 'User not part of List!'});
}
});
}
});
});
});
// List Settings. If $user is list.admin render admin settings
app.get('/list/:id/settings', requireLogin, function (req, res) {
List.findOne({_id: req.params.id}, function (err, list) {
if (err) {
res.render('index', {error: 'List not found!'});
}
verifyJWT(req.cookies.token, (err, userId) => {
User.findOne({_id: userId}, (err, user) => {
if (user.lists.indexOf(list._id) >= 0) {
if (list.admin.toString() === user._id.toString()) {
res.render('list-settings-admin', {
list: list, user: user
});
console.log("rendering " + list.name + "'s admin settings for user " + user.name);
}
else {
res.render('list-settings', {
list: list, user: user
});
console.log("rendering " + list.name + "'s settings for user " + user.name);
}
}
else {
console.log("User " + user.name + " is not member of List " + list.name);
res.redirect("/dashboard");
}
});
});
});
});
// Users Dashboard
app.get('/dashboard', requireLogin, (req, res) => {
verifyJWT(req.cookies.token, (err, userId) => {
User.findOne({_id: userId}, (err, user) => {
res.render('dashboard', {user: user});
});
});
});
// User Profile
app.get('/user', requireLogin, (req, res) => {
verifyJWT(req.cookies.token, (err, userId) => {
User.findOne({_id: userId}, (err, user) => {
res.render('settings-user', {user: user, apiToken:req.authentication.token});
});
});
});
// Invitations page for invited users to join a family and "sign up"
app.get('/list/:id/invitations/:invId', (req, res) => {
List.findOne({_id: req.params.id}, function (err, list) {
if (err) {
res.render('index', {error: 'List not found!', translate: res});
}
Invitation.findOne({_id: req.params.invId}, function (err, inv) {
if (err) {
res.render('index', {error: 'Invitation not found!', translate: res});
}
if (list.invitations.map(function (e) {
return e._id;
}).indexOf(inv._id)) {
// List exists and has an invitation for :name
// find user by inv id
User.findOne({email: inv.email}, (err, user) => {
if (user) {
User.findOneAndUpdate({_id: user._id}, {$push: {lists: inv.list}}, (err, update) => {
if (!err) {
res.redirect("/dashboard?newlist");
}
});
} else {
res.render('signup', {
list: list,
email: inv.email
});
}
});
}
else res.render('index', {error: 'Invitation not associated with List!'});
});
});
});
/**
* Basic Route to change the used language
*/
app.get("/language/:lang", (req, res) => {
res.cookie("preferredLang", req.params.lang, {maxAge: 9000000, httpOnly: true});
let url = req.get('Referrer') !== undefined ? req.get('Referrer') : "/";
res.redirect(url);
});
/**
* Standard User Route
*/
app.all('/', (req, res) => {
if (req.cookies.token) {
verifyJWT(req.cookies.token, (err, userId) => {
err && res.render("index", {user: false});
User.findOne({_id: userId}, (err, user) => {
if (user) res.render('index', {user: user});
else res.render('index', {user: false});
});
});
} else res.render('index', {user: false});
});
/**
* API Controller
*/
/**
* Lists API: Control Lists
* /api/lists
* @deprecated since v1.1.1
*/
// get all lists
app.get('/api/lists', requireAuthentication, deprecate, (req, res) => {
if (req.app.get('env') === 'development') {
// use mongoose to get all lists in the database
List.find(function (err, list) {
// if there is an error retrieving, send the error
if (err) {
res.json({success: false, error: 'No Lists Found!', code: 400})
}
res.json(list); // return all lists in JSON format
console.log(list);
});
}
});
// get single list
app.get('/api/lists/:id', requireAuthentication, (req, res) => {
List.findOne({_id: req.params.id}, function (err, list) {
if (req.authentication.user.lists.indexOf(list._id) >= 0) {
// if there is an error retrieving, send the error, nothing after res.send(err) will execute
if (err) {
res.json({success: false, error: 'List not found', code: 401})
}
res.json(list); // return the List in JSON format
console.log(list);
}
});
});
// get item-count of a list
app.get('/api/lists/:id/itemCount', requireAuthentication, (req, res) => {
List.findOne({_id: req.params.id}, function (err, list) {
if (req.authentication.user.lists.indexOf(list._id) >= 0) {
if (err) {
res.json({success: false, error: 'List not found', code: 401})
}
Item.find({list: list._id}, function (err, items) {
if (err) {
res.json({success: false, error: 'Items not found', code: 300})
}
res.json(items.length);
});
}
});
});
// get all invitaions for a list
app.get('/api/lists/:id/invitations', requireAuthentication, (req, res) => {
Invitation.find({list: req.params.id}, function (err, invitations) {
if (req.authentication.user.lists.indexOf(req.params.id) >= 0) {
if (err) {
res.json({success: false, error: 'No Invitations found for this List', code: 402});
}
res.json(invitations);
}
});
});
// create list
app.post('/api/lists', requireAuthentication, (req, res) => {
List.create({
name: req.body.name,
country: req.body.country,
admin: req.body.admin,
invitations: req.body.invitations
}, function (err, list) {
if (err) {
res.json({success: false, error: 'List not created!', code: 403});
}
res.json({success: true, id: list._id.toString()});
});
});
// let a user remove themselves from a list
app.post("/api/lists/:id/removeMeFromList", requireAuthentication, (req, res) => {
User.findOneAndUpdate({_id: req.authentication.user._id}, {$pull: {lists: req.params.id.toString()}}, {"new": true}, (err, user) => {
err && res.json({success: false, err: err});
res.json({success: true});
});
});
// remove a list
app.delete('/api/lists/:id/admin', requireAuthentication, (req, res) => {
let user = req.authentication.user._id;
List.findOne({_id: req.params.id}, (err, l) => {
if (l.admin.toString() === user.toString()) {
List.remove({_id: req.params.id}, function (err, list) {
if (err) {
res.json({success: false, error: 'List not removed', code: 404});
}
Item.remove({list:l._id.toString()}, (err, items) => {
res.json({success: true, list: list});
});
});
}
else res.json({success: false, error: 'User not List Admin'});
});
});
// remove all users except the admin from :list
app.delete("/api/lists/:id/removeAllUsers", requireAuthentication, (req, res) => {
let user = req.authentication.user._id;
List.findOne({_id: req.params.id}, (err, list) => {
console.log("err", err);
!!err && (res.json({success: false, err: err}));
if (list.admin.toString() === user.toString()) {
User.find({lists: list._id.toString()}, (err, users) => {
console.log("users: ", users);
users.forEach(user => {
if (list.admin.toString() === user._id.toString()) {
// keep user
console.log("keeping ", user.email);
} else {
User.update({_id: user._id}, {$pull: {lists: list._id.toString()}}, {"new": true}, (err, update) => {
!!err && res.json({success: false, err: err});
console.log("deleting ", user.email, update.lists)
});
}
});
res.json({success: true});
});
}
});
});
// delete list
app.delete('/api/lists/:id', requireAuthentication, (req, res) => {
let user = req.authentication.user._id.toString();
let list = req.params.id;
User.findOne({_id: user}, (err, u) => {
if (err) res.json({success: false}); // user not found
u.lists = u.lists.filter(e => e.id !== list);
User.findOneAndUpdate({_id: u._id}, {$set: {lists: u.lists}}, (err, u2) => {
if (err) res.json({success: false}); //user not updated
res.json({success: true});
});
});
});
/**
* List Settings:
*/
app.post("/api/lists/update/name", requireAuthentication, (req, res) => {
const {list, newName} = req.body;
let user = req.authentication.user._id.toString();
List.findOne({_id: list}).then(l => {
if (l.admin.toString() === user) {
List.update({_id: list}, {$set: {name: newName}}, (err, l2) => {
!!err && res.json({success: false, err: err});
res.json({success: true}); // reload page in js
});
}
});
});
app.post("/api/lists/update/country", requireAuthentication, (req, res) => {
let {list, newCountry, admin} = req.body;
admin = req.authentication.user._id.toString();
List.findOne({_id: list}).then(l => {
if (l.admin.toString() === admin) {
List.update({_id: list}, {$set: {country: newCountry}}, (err, l2) => {
!!err && res.json({success: false, err: err});
res.json({success: true}); // reload page in js
});
}
});
});
app.get("/api/lists/:id/userEmails", requireAuthentication, (req, res) => {
User.find({lists: req.params.id}, (err, users) => {
if (req.authentication.user.lists.indexOf(req.params.id) >= 0) {
!!err && res.json({success: false, err: err});
res.json({
success: true, users: users.map(u=> {
return {_id: u._id, email: u.email}
})
});
}
});
});
app.get("/api/lists/:id/invitationsForSettings", requireAuthentication, (req, res) => {
Invitation.find({list: req.params.id}, (err, invs) => {
if (req.authentication.user.lists.indexOf(req.params.id) >= 0) {
!!err && res.json({success: false, err: err});
res.json({
success: true, invitations: invs.map(i=> {
return {_id: i._id, email: i.email}
})
});
}
});
});
// update a list
/**
* @deprecated since v0.10.0
*/
app.post('/api/lists/:id', deprecate, (req, res) => {
let update = req.body;
List.findOneAndUpdate({_id: req.params.id}, update, function (err, list) {
if (err) {
res.json({error: 'List not updated', success: false, code: 405});
}
res.json({success: true, list: list});
});
});
/**
* Items API: Control Items
* /api/items
*/
// get all items per list
app.get('/api/items/:id', requireAuthentication, (req, res) => {
if (req.authentication.user.lists.indexOf(req.params.id) >= 0) {
// use mongoose to get all items in the database
Item.find({list: req.params.id}, function (err, items) {
// if there is an error retrieving, send the error. nothing after res.send(err) will execute
if (err) {
res.json({success: false, error: 'Items not found', code: 300});
}
res.json({success: true, items: items}); // return all items in JSON format
console.log(items);
});
}
});
// create item
app.post('/api/items', requireAuthentication, (req, res) => {
if (req.authentication.user.lists.indexOf(req.body.list) >= 0) {
if (!req.body.image) {
Item.create({
list: req.body.list,
name: req.body.name,
amount: req.body.amount,
art: req.body.art
}, function (err, item) {
if (err) {
res.json({success: false, error: 'Item not created', code: 301});
}
res.json(item);
});
} else {
cloudinary.uploader.upload(req.body.image, (result) => {
Item.create({
list: req.body.list,
name: req.body.name,
amount: req.body.amount,
art: req.body.art,
image: result["secure_url"],
"image_id": result["public_id"]
}, function (err, item) {
if (err) {
res.json({success: false, error: 'Item not created', code: 301});
}
res.json(item);
});
});
}
}
// TODO: don't add preset fields to list, loop through a mask and add the parameters that way
});
// remove an item
app.delete('/api/items/:id', requireAuthentication, (req, res) => {
Item.findOne({_id: req.params.id}, function (err, item) {
if (req.authentication.user.lists.indexOf(item.list.toString()) >= 0) {
Item.remove({_id: item._id}, (err, item2) => {
if (err) {
res.json({success: false, error: 'Item not removed', code: 302});
} else {
cloudinary.uploader.destroy(item["image_id"]);
res.json(item2);
}
});
}
});
});
// update an item
app.post('/api/items/:id', requireAuthentication, (req, res) => {
let update = req.body;
Item.findOneAndUpdate({_id: req.params.id}, update, function (err, item) {
if (err) {
res.json({success: false, error: 'Item not updated', code: 303});
}
res.json(item);
});
});