-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1319 lines (1082 loc) · 50.1 KB
/
index.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
/*
* ITINERARY BACKEND SERVER (REST API)
*
* This is the REST API server for Itinerary. It handles account operations and communicates with the MongoDB database.
*
* CREDITS:
* - Jeffalo for most of the authentication code
* - ScratchDB for verifying username cases
* - FluffyScratch for authentication
* - StackOverflow for complicated algorithms (see comments above specific functions)
*/
/*
* TODO:
* - Handle bad requests such as ones with plain % parameters
* - Tidy up and eliminate duplicate code; eliminate unnecessary indents because of if/else statements
* - Better and more consistent error handling
* - Add middleware for blocking requests from banned users
* - Validate game jam dates before saving them
* - Implement better pagination for game jams and projects
* - Support ordering projects by various criteria
*/
require('dotenv').config();
const fetch = require('node-fetch');
const crypto = require('crypto');
const express = require('express');
// Import Mongoose and the `Users` and `Sessions` models
const mongoose = require('mongoose');
const Users = require('./models/users');
const Sessions = require('./models/sessions');
const Jams = require('./models/jams');
const Projects = require('./models/projects');
const Upvotes = require('./models/upvotes');
const Managers = require('./models/managers');
// Make sure to not use deprecated features
mongoose.set('useNewUrlParser', true);
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useUnifiedTopology', true);
// Connect to MongoDB
mongoose
.connect(process.env.MONGO_URL)
.then(() => {
console.log('Connected to MongoDB!');
})
.catch((error) => {
console.log(`Failed to connect to MongoDB! Error: ${error}`);
});
const app = express();
const port = 8081;
let cors = require('cors');
const whitelist = ['http://localhost:3000', 'http://localhost:8081', process.env.FRONTEND_URL, process.env.BACKEND_URL];
const frontendURL = process.env.FRONTEND_URL;
const MAX_UPVOTES_PER_JAM = 3;
const corsOptions = {
origin: function (origin, callback) {
if (whitelist.indexOf(origin) !== -1 || !origin) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
};
// Use built-in middleware to recognize incoming request objects as JSON objects
app.use(express.json());
// Default response to root queries
app.get('/', async (req, res) => {
res.status(200).json({ meta: { version: 'v1', time: new Date() } });
});
/*
* General and user management endpoints
*/
app.options('/api/users', cors(corsOptions));
app.get('/api/users', cors(corsOptions), async (req, res) => {
if (!req.headers.authorization) {
res.status(401).json({ error: 'Authentication needed!' });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
return res.status(403).json({ error: `Only admins can get a list of users!` });
}
let userList = await Users.find({}).sort({ 'meta.updated': -1, _id: -1 }).exec();
res.status(200).json(userList);
}
});
app.options('/api/user/:name', cors(corsOptions));
app.put('/api/user/:name', cors(), async (req, res) => {
if (!req.headers.authorization) {
res.status(401).json({ error: 'You need auth!' });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (session.name.toLowerCase() !== req.params.name.toLowerCase() && !sessionUser.admin) {
return res.status(403).json({ error: 'You cannot edit other users unless you are an admin!' });
}
let user = await getUserData(req.params.name);
if (user) {
if (user.banned && !sessionUser.admin) return res.status(403).json({ error: { status: 403, code: 'banned', detail: 'You are banned from Itinerary!' } });
if (!req.params) {
return res.status(400).json({
error: {
status: 400,
code: 'userAlreadyExists',
detail: "This user already exists. If you are trying to update their account, please don't forget to send the necessary request parameters!",
},
});
}
let now = new Date();
if (sessionUser.admin) {
// Ban user
if (req.body.banned) {
await Users.updateOne({ name: user.name }, { $set: { banned: req.body.banned } });
await Sessions.deleteOne({ name: user.name });
} else {
await Users.updateOne({ name: user.name }, { $unset: { banned: '' } });
}
// Promote/demote user
if (req.body.admin) {
await Users.updateOne({ name: user.name }, { $set: { admin: req.body.admin } });
} else {
await Users.updateOne({ name: user.name }, { $unset: { admin: '' } });
}
}
await Users.updateOne({ name: user.name }, { $set: { 'meta.updatedBy': sessionUser.name, 'meta.updated': now.toISOString() } });
res.status(200).json({ ok: 'User updated!' });
} else {
if (req.params.name) {
// This is an admin trying to update a non-existent user thus we should create that user.
// Get the proper case of the username instead of whatever admin inputted
let scratchResponse = await fetch(`https://api.scratch.mit.edu/users/${req.params.name}/`);
let scratchData = await scratchResponse.json();
if (!scratchData.username) {
return res.status(404).json({ error: { status: 404, code: 'userNotFound', detail: 'This user could not be found on Scratch.' } });
}
let now = new Date();
await Users.create({
name: scratchData.username,
meta: {
updated: now.toISOString(),
updatedBy: session.name,
},
});
res.status(200).json({ ok: 'User added!' });
} else {
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'You must enter a username!' } });
}
}
}
});
app.delete('/api/user/:name', cors(), async (req, res) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
if (session.name.toLowerCase() !== req.params.name.toLowerCase()) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or the account owner!' } });
}
}
let user = await getUserData(req.params.name);
if (!user) {
return res.status(404).json({ error: "This user could not be deleted because it doesn't exist!" });
}
await Sessions.deleteOne({ name: user.name });
await Users.deleteOne({ name: user.name });
res.status(200).json({ ok: 'This user has been successfully deleted!' });
});
app.get('/api/user/:user/picture', cors(corsOptions), async (req, res) => {
let scratchResponse = await fetch(`https://api.scratch.mit.edu/users/${req.params.user}/`);
let scratchData = await scratchResponse.json();
let pictureURL = 'https://cdn2.scratch.mit.edu/get_image/user/0_90x90.png';
if (scratchData.profile) pictureURL = scratchData.profile.images['90x90'];
res.redirect(pictureURL);
});
/* --------------- */
/*
* Game jam endpoints
*/
app.options('/api/jams/:jam?', cors(corsOptions));
app.get('/api/jams/:jam?', cors(corsOptions), async (req, res) => {
// Parse `bypassMystery` URL parameter
const bypassMystery = req.query.bypassMystery === 'true';
if (!req.params.jam) {
// If we are NOT looking for a specific jam
const limit = req.query.limit || 40;
let offset = req.query.offset || 0;
if (offset < 0) offset = 0;
const { featured } = req.query;
let filterQuery = {};
if (featured != null || featured != undefined) {
if (featured == 'true') {
filterQuery.featured = true;
} else {
filterQuery.featured = { $ne: true };
}
}
// Get an array of all jams
let jamsCount = await Jams.countDocuments({});
let jamsList = await Jams.find(filterQuery).sort({ 'dates.start': 'descending' }).skip(Number(offset)).limit(Number(limit)).lean().exec();
// Loop through all jams and hide the title and main theme of jams that didn't start yet
if (bypassMystery) {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'Authentication needed!' });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: `Only admins and managers can view the details of upcoming jams!` });
}
}
} else {
let sessionUser = null;
if (req.headers.authorization) {
let session = findSession(req.headers.authorization);
if (session) {
sessionUser = await getUserData(session.name);
}
}
for (var i = 0; i < jamsList.length; i++) {
if (new Date(jamsList?.[i]?.['dates']?.['start']) > new Date() && jamsList?.[i]?.['options']?.['enableMystery'] === true) {
jamsList[i]['mystery'] = true;
if (sessionUser ? !sessionUser.admin && !(await sessionUser.isManager(jamsList?.[i]?.['slug'])) : true) {
// This jam is scheduled to start in the future. Therefore, we hide all content that could allow users to get an unfair head start
delete jamsList[i]['content']['body'];
delete jamsList[i]['content']['colors'];
//delete jamsList[i]['content']['headerImage'];
}
} else {
jamsList[i]['mystery'] = false;
}
}
}
res.status(200).json({ total: jamsCount, jams: jamsList });
} else {
// If we are looking for a specific jam
let jam = await Jams.findOne({ slug: req.params.jam }).lean();
if (jam) {
// Loop through all jams and hide the title and main theme of jams that didn't start yet
if (bypassMystery) {
if (!req.headers.authorization) {
res.status(401).json({ error: 'Authentication needed!' });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: `Only admins and managers can view the details of upcoming jams!` });
}
}
} else {
let sessionUser = null;
if (req.headers.authorization) {
let session = findSession(req.headers.authorization);
if (session) {
sessionUser = await getUserData(session.name);
}
}
if (new Date(jam['dates']['start']) > new Date() && jam?.['options']?.['enableMystery'] === true) {
jam['mystery'] = true;
if (sessionUser ? !sessionUser.admin && !(await sessionUser.isManager(jam['slug'])) : true) {
// This jam is scheduled to start in the future. Therefore, we hide all content that could allow users to get an unfair head start
delete jam['content']['body'];
delete jam['content']['colors'];
//delete jam['content']['headerImage'];
}
} else {
jam['mystery'] = false;
}
}
return res.status(200).json(jam);
} else {
return res.status(404).json({ error: { status: 404, code: 'jamNotFound', detail: 'The requested jam could not be found.' } });
}
}
});
app.put('/api/jams/:jam?', cors(corsOptions), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
res.status(401).json({ error: 'You need auth!' });
} else {
// Check whether the session is valid and the user has admin privileges
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!req.params.jam) {
// An admin is attempting to create a new jam
if (!sessionUser.admin) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin!' } });
}
let record = req.body;
let now = new Date();
let meta = {
meta: {
updated: now.toISOString(),
updatedBy: session.name,
},
};
// Append the `meta` object to the record
record = { ...record, ...meta };
// Create the new jam using
Jams.create(record)
.then((createdDocument) => {
return res.status(200).json({ ok: 'The jam was successfully created!', slug: createdDocument.slug });
})
.catch((e) => {
console.log(e);
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'One or more required parameters are missing from your query!' } });
});
} else {
// An admin or a manager is attempting to update a specific jam.
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or a manager!' } });
}
let now = new Date().toISOString();
// We are using the optional chaining operator (?.) to avoid errors when a specific property of the request body is undefined, as we will filter it later
let updateQuery = {
name: req?.body?.name,
dates: {
start: req?.body?.dates?.start,
end: req?.body?.dates?.end,
votingStart: req?.body?.dates?.votingStart,
votingEnd: req?.body?.dates?.votingEnd,
},
content: {
headerImage: req?.body?.content?.headerImage,
colors: req?.body?.content?.colors,
description: req?.body?.content?.description,
body: req?.body?.content?.body,
},
options: {
enableMystery: req?.body?.options?.enableMystery,
},
meta: {
updated: now,
updatedBy: session.name,
},
};
// Remove `undefined` and non-object values but keep `null`s, hence the `true` parameter
updateQuery = cleanObject(updateQuery, true);
// Retrieve the current jam and merge it with the cleaned, new jam
let jam = await Jams.findOne({ slug: req.params.jam }).lean();
if (!jam) {
return res.status(404).json({ error: { status: 404, code: 'jamNotFound', detail: 'The requested jam could not be found.' } });
}
if ((updateQuery?.dates?.end && new Date(updateQuery.dates.end).toISOString()) > now) {
// If the jam is ongoing, clear any winners
await Projects.updateMany({ jam: req.params.jam, $or: [{ selected: true }, { selectedByTheCommunity: true }] }, { selected: false, selectedByTheCommunity: false });
}
updateQuery = mergeObjects(jam, updateQuery);
// Update the jam and return the new slug
await Jams.findOneAndUpdate({ slug: req.params.jam }, { $set: updateQuery }, { new: true }).then((updatedDocument) => {
if (updatedDocument) {
if (updatedDocument.slug != req.params.jam) {
// "Re-link" managers to the game jam if its slug was modified
Managers.updateMany({ jam: req.params.jam }, { $set: { jam: updatedDocument.slug } }).exec();
}
return res.status(200).json({ ok: { newSlug: updatedDocument.slug } });
} else {
return res.status(404).json({ error: { status: 404, code: 'jamNotFound', detail: 'The requested jam could not be found.' } });
}
});
}
}
});
app.delete('/api/jams/:jam', cors(), async (req, res) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or a game jam manager!' } });
}
// Delete jam and all submissions associated with it
let jam = await Jams.findOne({ slug: req.params.jam });
if (jam) {
await Jams.deleteOne({ slug: req.params.jam });
await Projects.deleteMany({ jam: req.params.jam });
await Upvotes.deleteMany({ jam: req.params.jam });
await Managers.deleteMany({ jam: req.params.jam });
} else {
return res.status(404).json({ error: { status: 404, code: 'jamNotFound', detail: 'The requested jam could not be found.' } });
}
res.status(200).json({ ok: 'This jam has been successfully deleted!' });
});
app.options('/api/jams/:jam/managers/', cors(corsOptions));
app.get('/api/jams/:jam/managers', cors(corsOptions), async (req, res) => {
let managers = await Managers.find({ jam: req.params.jam });
return res.status(200).json({ managers: managers });
});
app.put('/api/jams/:jam/managers/', cors(corsOptions), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
res.status(401).json({ error: 'You need auth!' });
} else {
// Check whether the session is valid and the user has admin privileges
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or a moderator!' } });
}
let record = req.body;
record = { ...record, jam: req.params.jam };
if (await Managers.exists({ jam: record.jam, name: record.name })) {
return res.status(400).json({ error: { status: 409, code: 'recordAlreadyExists', detail: 'The requested user is already a manager in this jam!' } });
}
let user = await Users.exists({ name: record.name });
if (!user) {
return res.status(400).json({ error: { status: 400, code: 'userNotFound', detail: "This user doesn't exist in Itinerary's database!" } });
}
if ((await getUserData(record.name)).admin) {
return res.status(400).json({ error: { status: 400, code: 'userIsAdmin', detail: 'This user is an administrator thus they already have access to manager tools on every jam!' } });
}
// Add the new manager
Managers.create(record)
.then(() => {
return res.status(200).json({ ok: 'The manager was added to the jam!' });
})
.catch((e) => {
console.log(e);
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'One or more required parameters are missing from your query!' } });
});
}
});
app.delete('/api/jams/:jam/managers/', cors(), async (req, res) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
let record = req.body;
record = { ...record, jam: req.params.jam };
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or a manager!' } });
}
// Delete jam and all submissions associated with it
let manager = await Managers.findOne({ jam: record.jam, name: record.name });
if (manager) {
await Managers.deleteOne({ jam: record.jam, name: record.name });
} else {
return res.status(404).json({ error: { status: 404, code: 'managerNotFound', detail: 'The requested manager could not be found.' } });
}
res.status(200).json({ ok: 'The manager has been removed from this jam!' });
});
app.options('/api/jams/:jam/user-data/', cors(corsOptions));
app.get('/api/jams/:jam/user-data', cors(corsOptions), async (req, res) => {
if (!req.headers.authorization) {
res.status(401).json({ error: 'Authentication needed!' });
} else {
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
let isManager = await sessionUser.isManager(req.params.jam);
let hasParticipated;
let count = await Projects.countDocuments({ jam: req.params.jam, 'meta.submittedBy': session.name });
if (count > 0) {
hasParticipated = true;
} else {
hasParticipated = false;
}
res.status(200).json({ ok: { hasParticipated, manager: isManager } });
}
});
app.options('/api/jams/:jam/projects/:project?', cors(corsOptions));
app.get('/api/jams/:jam/projects/:project?', cors(), async (req, res) => {
let jam = await Jams.findOne({ slug: req.params.jam }).lean();
if (!jam) {
return res.status(404).json({ error: { status: 404, code: 'jamNotFound', detail: 'The requested jam could not be found.' } });
}
await computeCommunitySelectedWinner(req.params.jam);
if (!req.params.project) {
// If we are NOT looking for a specific project
const limit = req.query.limit;
let projectsList = await Projects.find({ jam: req.params.jam }).sort({ 'meta.submitted': 'descending' }).lean().exec();
if (!limit) {
// Return all projects
res.status(200).json(projectsList);
} else {
// Return a maximum of `limit` projects
res.status(200).json(projectsList.slice(0, limit));
}
} else {
// If we are looking for a specific project
let project = await Projects.findOne({ project: req.params.project }).lean();
if (!project) {
return res.status(404).json({ error: { status: 404, code: 'projectNotFound', detail: 'The requested project could not be found.' } });
}
return res.status(200).json(project);
}
});
app.put('/api/jams/:jam/projects/', cors(), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
// Prepare the record and verify whether the project exists
let record = req.body;
if (!record.project || !record.jam) {
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'You must provide both the `project` and `jam` parameters!' } });
}
let jam = await Jams.findOne({ slug: req.params.jam }).lean();
if (!jam) return res.status(400).json({ error: { status: 400, code: 'jamNotFound', detail: "The jam you are trying to submit a project to doesn't exist!" } });
let today = new Date().toISOString();
if (!((jam.dates.start && new Date(jam.dates.start).toISOString()) <= today && today < (jam.dates.end && new Date(jam.dates.end).toISOString()))) {
return res.status(403).json({ error: { status: 403, code: 'jamNotOpen', detail: 'This jam is not accepting submissions!' } });
}
/* let response = await fetch(`https://scratchdb.lefty.one/v3/project/info/${record.project}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
}); */
let response = await fetch(`https://api.allorigins.win/raw?url=https://api.scratch.mit.edu/projects/${record.project}?cache=${Date.now()}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
response = await response.json();
// TODO: Distinguish between different types of errors
if (response.code) {
return res.status(400).json({ error: { status: 400, code: 'badRequest', detail: "This project probably doesn't exist OR it is not shared!" } });
}
// Check whether the submitter is the owner of the project.
if (response?.author?.username !== session.name) {
return res.status(403).json({ error: { status: 403, code: 'illegalRequest', detail: 'You can only submit projects YOU own!' } });
}
// Check whether the project was already submitted
let count = await Projects.countDocuments({ project: record.project, jam: record.jam });
if (count > 0) {
return res.status(403).json({ error: { status: 403, code: 'alreadySubmitted', detail: 'This project is already submitted!' } });
}
let now = new Date();
let meta = {
meta: {
submitted: now.toISOString(),
submittedBy: session.name,
},
};
// Append the `meta` object to the record
record = { ...record, ...meta };
// Save the submission
await Projects.create(record)
.then(() => {
return res.status(200).json({ ok: 'Your submission was recorded' });
})
.catch((e) => {
console.log(e);
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'One or more required parameters are missing from your query!' } });
});
});
app.delete('/api/jams/:jam/projects/:project', cors(), async (req, res) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
if (!req.params.project) {
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'No project specified to delete.' } });
}
let project = await Projects.findOne({ project: req.params.project }).lean();
if (!project) {
return res.status(404).json({ error: { status: 404, code: 'projectNotFound', detail: 'The requested project could not be found.' } });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin && session.name !== project.meta.submittedBy && !(await sessionUser.isManager(req.params.jam))) {
return res
.status(403)
.json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin, a manager, or the person who submitted the project!' } });
}
// Delete the project and all upvotes associated with it
await Projects.deleteOne({ project: req.params.project, jam: req.params.jam });
await Upvotes.deleteMany({ project: req.params.project, jam: req.params.jam });
await computeCommunitySelectedWinner(req.params.jam);
res.status(200).json({ ok: 'Your submission was removed!' });
});
app.options('/api/jams/:jam/upvotes/:project?', cors(corsOptions));
app.get('/api/jams/:jam/upvotes/:project?', cors(), async (req, res) => {
if (!req.params.project) {
// If we are searching for the upvotes cast by the account that sent the request in a specific jam
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let upvotes = await Upvotes.find({ jam: req.params.jam, 'meta.upvotedBy': session.name });
let remainingUpvotes = MAX_UPVOTES_PER_JAM - upvotes.length;
return res.status(200).json({ ok: true, upvotes: upvotes, remainingUpvotes: remainingUpvotes });
} else {
// If we are looking for the TOTAL number of upvotes a project received in a specific game jam
let upvotes = await Upvotes.countDocuments({ jam: req.params.jam, project: req.params.project });
let upvotedByUser = false;
let extra = null;
if (req.headers.authorization) {
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
if ((await Upvotes.countDocuments({ jam: req.params.jam, project: req.params.project, 'meta.upvotedBy': session.name })) > 0) {
upvotedByUser = true;
}
extra = { upvoted: upvotedByUser };
}
return res.status(200).json({ ok: true, count: upvotes, ...extra });
}
});
app.put('/api/jams/:jam/upvotes/:project?', cors(), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
// Prepare the record
let record = { jam: req.params.jam, project: req.params.project };
if (!record.project || !record.jam) {
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'Your request is incomplete!' } });
}
// Check whether the user is within the upvote limit per game jam
let upvotes = await Upvotes.countDocuments({ jam: req.params.jam, 'meta.upvotedBy': session.name });
let remainingUpvotes = upvotes - MAX_UPVOTES_PER_JAM;
if (remainingUpvotes === 0) {
return res.status(403).json({
error: {
status: 403,
code: 'tooManyUpvotes',
detail: `You can only upvote ${MAX_UPVOTES_PER_JAM} ${
MAX_UPVOTES_PER_JAM == 1 ? 'project' : 'projects'
} per game jam! This limit exists to encourage users to evaluate each project, possibly leave some constructive feedback, and carefully consider which projects they should upvote.`,
},
});
}
// Check whether the upvote was already cast
let count = await Upvotes.countDocuments({ project: record.project, jam: record.jam, 'meta.upvotedBy': session.name });
if (count > 0) {
return res.status(403).json({ error: { status: 403, code: 'alreadySubmitted', detail: 'You have already cast a vote on this project!' } });
}
let now = new Date();
let meta = {
meta: {
upvoted: now.toISOString(),
upvotedBy: session.name,
},
};
// Append the `meta` object to the record
record = { ...record, ...meta };
// Save the submission
await Upvotes.create(record)
.then(() => {
return res.status(200).json({ ok: 'Your vote was saved' });
})
.catch((e) => {
console.log(e);
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'One or more required parameters are missing from your query!' } });
});
});
app.delete('/api/jams/:jam/upvotes/:project?', cors(), async (req, res) => {
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
if (!req.params.project) {
await Upvotes.deleteMany({ jam: req.params.jam });
}
// Delete the project and all upvotes associated with it
let { deletedCount } = await Upvotes.deleteOne({ project: req.params.project, jam: req.params.jam, 'meta.upvotedBy': session.name });
if (deletedCount > 0) {
res.status(200).json({ ok: 'Your upvote was removed!' });
} else {
return res.status(404).json({ error: { status: 404, code: 'upvoteNeverCast', detail: 'No upvotes were cast for this project during this jam.' } });
}
});
app.options('/api/jams/:jam/winners/', cors(corsOptions));
app.get('/api/jams/:jam/winners/', cors(), async (req, res) => {
await computeCommunitySelectedWinner(req.params.jam);
let winners = await Projects.find({ jam: req.params.jam, $or: [{ selected: true }, { selectedByTheCommunity: true }] });
return res.status(200).json({ winners: winners });
});
app.put('/api/jams/:jam/winners/', cors(), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
// Prepare the record and verify whether the project exists
let record = req.body;
if (!record.project) {
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'You must provide the `project` parameter!' } });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or a manager!' } });
}
await Projects.updateMany({ jam: req.params.jam, project: { $ne: record.project } }, { selected: false });
await Projects.updateOne({ jam: req.params.jam, project: record.project }, { selected: true, selectedByTheCommunity: false });
await computeCommunitySelectedWinner(req.params.jam);
return res.status(200).json({ ok: 'The requested project was selected as the winner.' });
});
app.delete('/api/jams/:jam/winners/', cors(), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
// Prepare the record and verify whether the project exists
let record = req.body;
if (!record.project) {
return res.status(400).json({ error: { status: 400, code: 'missingParameters', detail: 'You must provide the `project` parameter!' } });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin && !(await sessionUser.isManager(req.params.jam))) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin or a manager!' } });
}
await Projects.updateOne({ jam: req.params.jam, project: record.project }, { selected: false });
await computeCommunitySelectedWinner(req.params.jam);
return res.status(200).json({ ok: 'The requested project was stripped of the winner status.' });
});
app.options('/api/jams/:jam/feature/', cors(corsOptions));
app.put('/api/jams/:jam/feature/', cors(), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin!' } });
}
await Jams.updateOne({ slug: req.params.jam }, { featured: true });
return res.status(200).json({ ok: 'The requested jam was featured.' });
});
app.delete('/api/jams/:jam/feature/', cors(), async (req, res) => {
// Verify that the `Authorization` header was sent with the request
if (!req.headers.authorization) {
return res.status(401).json({ error: 'You need auth!' });
}
// Check whether the session is valid
let session = findSession(req.headers.authorization);
if (!session) {
return res.status(403).json({ error: 'Invalid auth!' });
}
let sessionUser = await getUserData(session.name);
if (!sessionUser.admin) {
return res.status(403).json({ error: { status: 403, code: 'insufficientPermissions', detail: 'This action can only be performed by an admin!' } });
}
await Jams.updateOne({ slug: req.params.jam }, { featured: false });
return res.status(200).json({ ok: 'The requested jam was unfeatured.' });
});
async function computeCommunitySelectedWinner(jam) {
/*