forked from PenguinMod/PenguinMod-IntermediateBackendApi
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
3125 lines (3007 loc) · 117 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
// return;
require('dotenv').config();
const BlockedIPs = require("./blockedips.json"); // if you are cloning this, make sure to make this file
const fs = require("fs");
const jimp = require("jimp");
const JSZip = require("jszip");
const Database = require("easy-json-database");
const Cast = require("./classes/Cast.js");
const DEBUG_logAllFailedData = Cast.toBoolean(process.env.LogFailedData);
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const rateLimit = require('express-rate-limit');
const app = express();
const port = 8080;
let globalOperationCounter = 0;
const { encrypt, decrypt } = require("./utilities/encrypt.js");
const UserManager = require("./classes/UserManager.js");
//const UserStorage = require("./classes/UserStorage.js");
//const StorageSpace = new UserStorage(32000000, 3); // 32 mb per data piece, 3 keys per container
UserManager.load(); // should prevent logouts
const ProjectList = require("./classes/ProjectList.js");
const GenericList = require("./classes/GenericList.js");
const ReportList = require("./classes/ReportList.js");
const AdminAccountUsernames = new Database(`${__dirname}/admins.json`);
const ApproverUsernames = new Database(`${__dirname}/approvers.json`);
const GlobalRuntimeConfig = new Database(`${__dirname}/globalsettings.json`);
// UserManager.setCode('debug', 'your-mom');
app.use(express.json({ limit: '25mb' })); // Adjust the limit as needed
app.use(express.urlencoded({ extended: true, limit: '25mb' })); // Adjust the limit
function DecryptArray(array) {
const na = [];
for (const value of array) {
const decrypted = decrypt(value);
na.push(decrypted);
}
return na;
}
app.use((req, res, next) => {
// Allow requests from both 'https://snail-ide.vercel.app' and 'https://snail-ide.js.org'
res.header('Access-Control-Allow-Origin', 'https://snail-ide.vercel.app/', 'https://snail-ide.js.org');
// You can also use '*' to allow any origin, but this is less secure
// res.header('Access-Control-Allow-Origin', '*');
next();
});
function SafeJSONParse(json) {
try {
return JSON.parse(json);
} catch {
return {};
}
}
const inList = require("./illegalwords.js");
const CheckForIllegalWording = (...args) => {
for (const argument of args) {
for (const illegalWord of inList) {
const checking = Cast.toString(argument)
.toLowerCase()
.replace(/[ _\-!?.#/\\,'"@$%^&*\(\)]+/gmi, '');
if (checking.includes(illegalWord)) {
return true;
}
}
}
return false;
};
// Example usage:
const containsIllegalWord = CheckForIllegalWording("Some text with word2", "Another text without illegal words");
console.log(containsIllegalWord); // Output: true or false based on whether any illegal word is found
function Deprecation(res, reason = "") { // if an endpoint is deprecated, use this.
res.status(400);
res.header("Content-Type", 'application/json');
res.json({
error: "Deprecated Endpoint",
reason
});
}
function escapeXML(unsafe) {
if (typeof unsafe !== 'string') {
if (unsafe) {
// This happens when we have hacked blocks from 2.0
// See #1030
unsafe = String(unsafe);
} else {
console.error(`Unexptected type ${typeof unsafe} in xmlEscape at: ${new Error().stack}`)
return unsafe;
}
}
return unsafe.replace(/[<>&'"\n]/g, c => {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
case '\n': return ' '
}
});
};
/**
* Returns either a JSZip instance or null.
* @param {Buffer} buffer
* @param {JSZip.JSZipLoadOptions} options
* @returns {Promise<JSZip?>}
*/
const safeZipParse = (buffer, options) => {
return new Promise((resolve) => {
if (!buffer) return resolve();
JSZip.loadAsync(buffer, options).then(zip => {
resolve(zip);
}).catch(() => {
resolve();
});
});
};
const illegalExtensionsList = require("./illegalextensions.json");
const checkExtensionIsAllowed = (extension, isUrl) => {
if (!extension) return true;
let propertyName = "id";
if (isUrl) {
propertyName = "url";
}
const extensionsConfig = illegalExtensionsList[propertyName];
const isIncluded = extensionsConfig.items.includes(extension);
const isBlacklist = extensionsConfig.useAsWhitelist !== true;
if (isBlacklist && isIncluded) {
return false;
}
if (!isBlacklist && isIncluded) {
return true;
}
if (!isBlacklist && !isIncluded) {
return false;
}
return true; // isBlacklist and isntIncluded
};
app.use(cors({
origin: '*',
optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
}));
app.use(bodyParser.urlencoded({
limit: process.env.ServerSize,
extended: false
}));
app.use(bodyParser.json({ limit: process.env.ServerSize }));
app.use((req, res, next) => {
if (BlockedIPs.includes(req.ip)) return res.sendStatus(403);
console.log(`${req.ip}: ${req.originalUrl}`);
next();
});
app.set('trust proxy', 1);
app.use(rateLimit({
validate: {
trustProxy: true,
xForwardedForHeader: true,
},
windowMs: 5000, // 150 requests per 5 seconds
limit: 150,
standardHeaders: 'draft-7',
legacyHeaders: false,
}));
app.get('/', async function (_, res) { // just basic stuff. returns the home page
res.redirect('https://snail-ide.vercel.app/');
});
app.get('/robots.txt', async function (_, res) { // more basic stuff!!!!! returns robots.txt
res.sendFile(path.join(__dirname, './robots.txt'));
});
// get API metadata
app.get('/api', async function (_, res) {
res.status(200);
res.header("Content-Type", 'application/json');
res.sendFile(path.join(__dirname, './metadata.json'));
});
// PING COMMAND TO CHECK IF API IS WORKING (LOL)
app.get('/api/ping', async function (_, res) {
res.send("Pong!")
});
const projectTemplate = fs.readFileSync('./project.html').toString();
app.get('/:id', async function (req, res) {
const db = new Database(`${__dirname}/projects/published.json`);
const json = db.get(String(req.params.id));
if (!json) {
res.sendFile(path.join(__dirname, './404-noproject.html'));
return;
}
res.status(200);
let html = projectTemplate
for (const prop in json) {
html = html.replaceAll(`{project.${prop}}`, escapeXML(json[prop]));
}
res.send(html);
});
// profile stuff
const GenerateProfileJSON = (username) => {
const rawBadges = UserManager.getProperty(username, "badges");
const badges = Array.isArray(rawBadges) ? rawBadges : [];
const isDonator = badges.includes('donator');
let rank = UserManager.getProperty(username, "rank");
if (typeof rank !== "number") rank = 0;
const signInDate = UserManager.getProperty(username, "firstLogin") || Date.now();
const projectsDatabase = new Database(`${__dirname}/projects/published.json`);
const userProjects = projectsDatabase.all()
.map(value => { return value.data })
.filter(project => (project.owner === username));
const canRequestRankUp = (userProjects.length > 3 // if we have 3 projects and
&& (Date.now() - signInDate) >= 4.32e+8) // first signed in 5 days ago
|| badges.length > 0; // or we have a badge
const followers = UserManager.getFollowers(username);
return {
username,
admin: AdminAccountUsernames.get(username),
approver: ApproverUsernames.get(username),
banned: UserManager.isBanned(username), // skipped in /profile but provided in /usernameFromCode
badges,
donator: isDonator,
rank,
followers: followers.length,
canrankup: canRequestRankUp && rank === 0,
viewable: userProjects.length > 0,
projects: userProjects.length // we check projects anyways so might aswell
};
};
app.get('/api/users/profile', async function (req, res) { // check if user is banned
const username = Cast.toString(req.query.username);
if (typeof username !== "string") {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "NoUserSpecified" });
return;
}
if (UserManager.isBanned(username)) {
res.status(404);
res.header("Content-Type", 'application/json');
res.json({ "error": "NotFound" });
return;
}
res.status(200);
res.header("Content-Type", 'application/json');
res.json(GenerateProfileJSON(username));
});
app.post('/api/users/requestRankUp', async function (req, res) {
const packet = req.body;
if (!UserManager.isCorrectCode(packet.username, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
const username = Cast.toString(packet.username);
const rawBadges = UserManager.getProperty(username, "badges");
const badges = Array.isArray(rawBadges) ? rawBadges : [];
let rank = UserManager.getProperty(username, "rank");
if (typeof rank !== "number") rank = 0;
if (rank !== 0) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "AlreadyRankedHighest" });
return;
}
const signInDate = UserManager.getProperty(username, "firstLogin") || Date.now();
const projectsDatabase = new Database(`${__dirname}/projects/published.json`);
const userProjects = projectsDatabase.all()
.map(value => { return value.data })
.filter(project => (project.owner === username));
const canRequestRankUp = (userProjects.length > 3 // if we have 3 projects and
&& (Date.now() - signInDate) >= 4.32e+8) // first signed in 5 days ago
|| badges.length > 0; // or we have a badge
if (!canRequestRankUp) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "Ineligble" });
return;
}
UserManager.setProperty(username, "rank", 1);
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": true });
});
// security stuff i guess :idk_man:
app.get('/api/users/isBanned', async function (req, res) { // check if user is banned
if (typeof req.query.username != "string") {
res.status(400)
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidRequest" })
return
}
res.status(200)
res.header("Content-Type", 'application/json');
res.json({ "banned": UserManager.isBanned(req.query.username) })
});
app.get('/api/users/assignPossition', async function (req, res) { // give someone admin or approver (only admins can use this)
const packet = req.query;
if (!UserManager.isCorrectCode(packet.user, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (!AdminAccountUsernames.get(Cast.toString(packet.user))) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "FeatureDisabledForThisAccount" });
return;
}
AdminAccountUsernames.set(packet.target, Cast.toBoolean(packet.admin));
ApproverUsernames.set(packet.target, Cast.toBoolean(packet.approver));
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": 'AppliedStatus' });
});
app.get('/api/errorAllProjectRequests', async function (req, res) { // set the state of allowing or preventing all project info getting requests (only admins can use this)
const packet = req.query;
if (!UserManager.isCorrectCode(packet.user, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (!AdminAccountUsernames.get(Cast.toString(packet.user))) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "FeatureDisabledForThisAccount" });
return;
}
GlobalRuntimeConfig.set("allowGetProjects", Cast.toBoolean(packet.enabled));
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": 'AppliedStatus' });
});
// get approved projects
app.get('/api/projects/getApproved', async function (req, res) {
if (GlobalRuntimeConfig.get("allowGetProjects") === false) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "FeatureDisabledForThisAccount" });
return;
}
const db = new Database(`${__dirname}/projects/published.json`);
// this is explained in paged api but basically just add normal projects to featured projects
// because otherwise featured projects would come after normal projects
const featuredProjects = [];
const projects = db.all().map(value => { return value.data }).sort((project, sproject) => {
return sproject.date - project.date;
}).filter(proj => proj.accepted === true).filter(project => {
if (project.featured) {
featuredProjects.push(project);
}
return project.featured != true;
});
let returnArray = featuredProjects.concat(projects);
if (Cast.toBoolean(req.query.reverse)) {
returnArray = structuredClone(returnArray).reverse();
}
// make project list
// new ProjectList() with .toJSON will automatically cut the pages for us
const projectsList = new ProjectList(returnArray);
const returning = projectsList.toJSON(true, Cast.toNumber(req.query.page));
res.header("Content-Type", 'application/json');
res.status(200);
res.json(returning);
});
// get approved projects but only a certain amount
app.get('/api/projects/max', async function (req, res) {
if (GlobalRuntimeConfig.get("allowGetProjects") === false) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "FeatureDisabledForThisAccount" });
return;
}
function grabArray() {
const db = new Database(`${__dirname}/projects/published.json`)
// this is explained in paged api but basically just add normal projects to featured projects
// because otherwise featured projects would come after normal projects
const featuredProjects = [];
const projects = db.all().map(value => { return value.data }).sort((project, sproject) => {
return sproject.date - project.date;
}).filter(proj => proj.accepted === true).filter(project => {
if (project.featured) {
featuredProjects.push(project);
}
return project.featured != true;
})
if (String(req.query.featured) == "true") {
return featuredProjects;
}
if (String(req.query.hidefeatured) == "true") {
return projects;
}
const returnArray = featuredProjects.concat(projects);
return returnArray;
}
let count = Number(req.query.amount);
if (isNaN(count)) count = 0;
if (!isFinite(count)) count = 0;
if (count < 0) count = 0;
if (count > 20) count = 20;
count = Math.round(count);
const arr = grabArray().slice(0, count);
const projectsList = new ProjectList(arr);
const returning = projectsList.toArray(false);
res.header("Content-Type", 'application/json');
res.status(200);
res.json(returning);
});
// get unapproved projects
app.get('/api/projects/getUnapproved', async function (req, res) {
// 6/3/2023 unapproved projects are admin only
const packet = req.query;
if (!UserManager.isCorrectCode(packet.user, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (
!AdminAccountUsernames.get(Cast.toString(packet.user))
&& !ApproverUsernames.get(Cast.toString(packet.user))
) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "ThisAccountCannotAccessThisInformation" });
return;
}
const db = new Database(`${__dirname}/projects/published.json`)
const projects = db.all().map(value => { return value.data }).sort((project, sproject) => {
return sproject.date - project.date;
}).filter(proj => proj.accepted === false);
let returnArray = projects;
if (Cast.toBoolean(req.query.reverse)) {
returnArray = structuredClone(returnArray).reverse();
}
const projectsList = new ProjectList(returnArray);
const returning = projectsList.toJSON(true, Cast.toNumber(req.query.page));
res.header("Content-Type", 'application/json');
res.status(200);
res.json(returning);
});
// pm wrappers so that pm code doesnt need to be changed in a major way
app.get('/api/pmWrapper/projects', async function (req, res) { // add featured projects and normal projects together
const db = new Database(`${__dirname}/projects/published.json`)
// this is explained in paged api but basically just add normal projects to featured projects
// because otherwise featured projects would come after normal projects
const featuredProjects = []
const projects = db.all().map(value => { return value.data }).sort((project, sproject) => {
return sproject.date - project.date;
}).map(project => {
return { id: project.id, name: project.name, author: { username: project.owner }, accepted: project.accepted, featured: project.featured };
}).filter(proj => proj.accepted === true).filter(project => {
if (project.featured) {
featuredProjects.push(project);
}
return project.featured != true;
});
const returnArray = featuredProjects.concat(projects);
const projectsList = new ProjectList(returnArray);
const returning = projectsList.toJSON(true, Cast.toNumber(req.query.page));
res.header("Content-Type", 'application/json');
res.status(200);
res.json(returning);
});
app.get('/api/pmWrapper/remixes', async function (req, res) { // get remixes of a project
const packet = req.query;
if (!packet.id) {
res.status(400);
res.json({ "error": "IdNotSpecified" });
return;
}
const db = new Database(`${__dirname}/projects/published.json`);
// we dont care about featured projects here because remixes cant be featured
const json = db.all().map(value => { return value.data }).sort((project, sproject) => {
return sproject.date - project.date;
}).filter(proj => proj.remix == packet.id).filter(proj => proj.accepted === true);
const projectsList = new ProjectList(json);
const returning = projectsList.toJSON(true, Cast.toNumber(req.query.page));
res.header("Content-Type", 'application/json');
res.status(200);
res.json(returning);
});
app.get('/api/pmWrapper/iconUrl', async function (req, res) { // get icon url of a project
if (!req.query.id) {
res.status(400);
res.json({ "error": "IdNotSpecified" });
return;
}
const db = new Database(`${__dirname}/projects/published.json`);
const json = db.get(String(req.query.id));
if (!json) {
res.status(400);
res.json({ "error": "IdNotValid" });
return;
}
fs.readFile(`./projects/uploadedImages/p${json.id}.png`, (err, buffer) => {
if (err) {
res.status(404);
res.json({
"error": "ImageNotFoundOrErrorOccurred",
"realerror": String(err)
});
return;
}
jimp.read(buffer).then(async image => {
const width = Cast.toBoolean(req.query.widescreen) ? 640 : 480;
image.cover(width / 2, 360 / 2, async (err, image) => {
if (err) {
res.status(500);
res.json({
"error": "CompressionCroppingError",
"realerror": String(err)
});
return;
}
const buffer = await image.getBufferAsync(jimp.MIME_JPEG);
res.status(200);
res.contentType(jimp.MIME_JPEG);
res.send(buffer);
});
}).catch(err => {
res.status(500);
res.json({
"error": "CompressionError",
"realerror": String(err)
});
return;
});
});
});
app.get('/api/pmWrapper/getProject', async function (req, res) { // get data of a(n approved) project
if (!req.query.id) {
res.status(400);
res.json({ "error": "IdNotSpecified" });
return;
}
const db = new Database(`${__dirname}/projects/published.json`);
const json = db.get(String(req.query.id));
if (!json) {
res.status(400);
res.json({ "error": "IdNotValid" });
return;
}
res.status(200);
res.json({ id: json.id, name: json.name, author: { id: -1, username: json.owner, } });
});
// scratch auth implementation
app.get('/api/users/login', async function (req, res) { // login with scratch
const privateCode = Cast.toString(req.query.privateCode);
UserManager.verifyCode(privateCode).then(response => {
// check if it is a malicious site
// note: malicious sites cannot read the private code in the URL if it is the right redirect
// thank you cors, you finally did something useful
// malicious APPS could, but at that point your just :trollface:d so :idk_man:
const invalidRedirect = response.redirect !== 'https://snailshare-server.onrender.com/api/users/login';
if ((!response.valid) || (invalidRedirect)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidLogin" });
if (invalidRedirect) {
console.log(response.redirect, "tried to falsely authenticate", response.username);
}
return;
}
// todo: we should clear the login after a couple days or so
const username = response.username;
UserManager.setCode(username, privateCode);
if (!UserManager.getProperty(username, "firstLogin")) {
UserManager.setProperty(username, "firstLogin", Date.now());
}
// close window by opening success.html
res.header("Content-Type", 'text/html');
res.status(200);
res.sendFile(path.join(__dirname, "./success.html"));
}).catch(() => {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidLogin" });
});
});
app.get('/api/users/loginLocal', async function (req, res) { // login with local account (like localhost)
const privateCode = Cast.toString(req.query.privateCode);
UserManager.verifyCode(privateCode).then(response => {
// check if it is a malicious site
// note: malicious sites cannot read the private code in the URL if it is the right redirect
// thank you cors, you finally did something useful
// malicious APPS could, but at that point your just :trollface:d so :idk_man:
const invalidRedirect =
response.redirect !== 'https://snailshare-server.onrender.com/api/users/loginLocal'
&& response.redirect !== 'http://localhost:8080/api/users/loginLocal';
if ((!response.valid) || (invalidRedirect)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidLogin" });
if (invalidRedirect) {
console.log(response.redirect, "tried to falsely authenticate", response.username);
}
return;
}
// todo: we should clear the login after a couple days or so
const username = response.username;
UserManager.setCode(username, privateCode);
if (!UserManager.getProperty(username, "firstLogin")) {
UserManager.setProperty(username, "firstLogin", Date.now());
}
// close window by opening success.html
res.header("Content-Type", 'text/html');
res.status(200);
res.sendFile(path.join(__dirname, "./success_local.html"));
}).catch(() => {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidLogin" });
});
});
// logout
app.get('/api/users/logout', (req, res) => { // logout
if (!UserManager.isCorrectCode(req.query.user, req.query.code)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidLogin" });
return;
}
UserManager.logoutUser(req.query.user);
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": "LoginIsNowInvalidated" });
});
app.get('/api/users/usernameFromCode', async function (req, res) { // get username from private code
const privateCode = Cast.toString(req.query.privateCode);
const username = UserManager.usernameFromCode(privateCode);
if (username == null) {
res.status(404);
res.header("Content-Type", 'application/json');
res.json({ "error": "CodeNotFound" });
return;
}
res.status(200);
res.header("Content-Type", 'application/json');
res.json(GenerateProfileJSON(Cast.toString(username)));
});
// extra stuff
app.get('/api/users/isAdmin', async function (req, res) { // check if user is admin (by username)
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "admin": AdminAccountUsernames.get(Cast.toString(req.query.username)) });
});
app.get('/api/users/isApprover', async function (req, res) { // check if user is approver (by username)
res.status(200);
res.header("Content-Type", 'application/json');
res.json({
"approver": ApproverUsernames.get(Cast.toString(req.query.username))
|| AdminAccountUsernames.get(Cast.toString(req.query.username))
});
});
app.get('/api/users/getMyProjects', async function (req, res) { // get projects of a user (need username and private code)
if (!UserManager.isCorrectCode(req.query.user, req.query.code)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
const db = new Database(`${__dirname}/projects/published.json`);
const projects = db.all().map(data => data.data).filter(project => project.owner === req.query.user);
let result = projects;
if (String(req.query.sorted) === "true") {
result.sort((project, sproject) => {
return sproject.date - project.date
});
const featuredProjects = [];
const waitingProjects = [];
const hiddenProjects = [];
result = result.filter(project => {
if (project.featured) {
featuredProjects.push(project);
return false;
}
if (!project.accepted) {
waitingProjects.push(project);
return false;
}
if (project.hidden) {
hiddenProjects.push(project);
return false;
}
return true;
})
const returnArray = featuredProjects.concat(result, waitingProjects, hiddenProjects);
result = returnArray;
}
// paginate
const projectsList = new ProjectList(result);
const returning = projectsList.toJSON(true, Cast.toNumber(req.query.page));
res.status(200)
res.header("Content-Type", 'application/json');
res.json(returning)
});
// MESSAGES
app.get('/api/users/getMessages', async function (req, res) { // get a users messages (you have to be the user) (by username and private code)
const packet = req.query;
if (!UserManager.isCorrectCode(packet.username, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
const messages = UserManager.getMessages(packet.username);
const messageList = new GenericList(messages);
const returning = messageList.toJSON(true, Cast.toNumber(req.query.page));
res.status(200);
res.header("Content-Type", 'application/json');
res.json(returning);
});
// we might not actually need this endpoint tbh
app.post('/api/users/addMessage', async function (req, res) { // add a message to a user (you have to be the user) (by username and private code)
const packet = req.body;
if (!UserManager.isCorrectCode(packet.username, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
// validate message (do we have perms? is this a valid message?)
const unsafeMessage = packet.message;
const invalidate = () => {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "InvalidMessage" });
};
const notallowed = () => {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "CannotSendThisMessageType" });
};
// is this actually a message object?
if (typeof unsafeMessage !== "object") return invalidate();
if (Array.isArray(unsafeMessage)) return invalidate();
// is the type of this message actually decided?
if (typeof unsafeMessage.type !== "string") return invalidate();
// check message type & add it
const username = Cast.toString(packet.username);
const target = packet.target;
switch (unsafeMessage.type) {
case 'custom':
if (!AdminAccountUsernames.get(username)) return notallowed();
if (typeof unsafeMessage.text !== "string") return invalidate();
UserManager.addMessage(target, {
type: unsafeMessage.type,
text: unsafeMessage.text
});
break;
default:
return invalidate();
}
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": true });
});
app.get('/api/users/getMessageCount', async function (req, res) { // get a users message count (you have to be the user) (by username and private code)
const packet = req.query;
if (!UserManager.isCorrectCode(Cast.toString(packet.username), packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
const messages = UserManager.getUnreadMessages(Cast.toString(packet.username));
res.status(200);
res.header("Content-Type", 'text/plain');
res.send(String(messages.length));
});
app.post('/api/users/markMessagesAsRead', async function (req, res) {
const packet = req.body;
if (!UserManager.isCorrectCode(packet.username, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (packet.id) {
UserManager.modifyMessage(packet.username, packet.id, (message) => ({
...message,
read: true
}));
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": true });
return;
}
if (packet.ids) {
if (!Array.isArray(packet.ids)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "IDsMustBeArray" });
return;
}
for (const id of packet.ids) {
UserManager.modifyMessage(packet.username, id, (message) => ({
...message,
read: true
}));
}
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": true });
return;
}
UserManager.markMessagesAsRead(packet.username);
res.status(200);
res.header("Content-Type", 'application/json');
res.json({ "success": true });
});
// BADGES
app.get('/api/users/getBadges', async function (req, res) { // get a users badges (by username)
const packet = req.query;
if (typeof packet.username !== "string") {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "UsernameMustBeString" });
return;
}
if (!packet.username) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "UsernameNotSpecified" });
return;
}
const badges = UserManager.getProperty(packet.username, "badges");
if (!Array.isArray(badges)) {
res.status(200);
res.header("Content-Type", 'application/json');
res.json([]);
return;
}
res.status(200);
res.header("Content-Type", 'application/json');
res.json(badges);
});
app.post('/api/users/setBadges', async function (req, res) { // set a users badges (you must be an admin) (by username)
const packet = req.body;
if (!UserManager.isCorrectCode(Cast.toString(packet.username), packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (!AdminAccountUsernames.get(Cast.toString(packet.username))) {
res.status(403);
res.header("Content-Type", 'application/json');
res.json({ "error": "FeatureDisabledForThisAccount" });
return;
}
const newBadges = packet.badges;
const target = packet.target;
if (typeof target !== "string") {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "TargetMustBeString" });
return;
}
if (!target) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "TargetNotSpecified" });
return;
}
if (!Array.isArray(newBadges)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "BadgesMustBeArray" });
return;
}
UserManager.setProperty(target, "badges", newBadges);
res.status(200);
res.header("Content-Type", 'application/json');
res.json({
success: true,
newbadges: UserManager.getProperty(target, "badges")
});
});
// following
app.get('/api/users/getFollowerCount', async function (req, res) { // get a users follower count (by username)
const packet = req.query;
if (typeof packet.username !== "string") {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "UsernameMustBeString" });
return;
}
if (!packet.username) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "UsernameNotSpecified" });
return;
}
const followers = UserManager.getFollowers(packet.username);
if (!Array.isArray(followers)) {
res.status(200);
res.header("Content-Type", 'text/plain');
res.send("0");
return;
}
res.status(200);
res.header("Content-Type", 'text/plain');
res.send(Cast.toString(followers.length));
});
app.get('/api/users/isFollowing', async function (req, res) { // check if a user is following another user (by username)
const packet = req.query;
if (typeof packet.username !== "string") {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "UsernameMustBeString" });
return;
}
if (!UserManager.isCorrectCode(packet.username, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (!packet.target) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "TargetNotSpecified" });
return;
}
const followers = UserManager.getFollowers(packet.target);
if (!Array.isArray(followers)) {
res.status(200);
res.header("Content-Type", 'application/json');
res.json({
following: false,
count: 0
});
return;
}
res.status(200);
res.header("Content-Type", 'application/json');
res.json({
following: followers.includes(packet.username),
count: followers.length
});
});
app.post('/api/users/followToggle', async function (req, res) {
const packet = req.body;
if (typeof packet.username !== "string") {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "UsernameMustBeString" });
return;
}
if (!UserManager.isCorrectCode(packet.username, packet.passcode)) {
res.status(400);
res.header("Content-Type", 'application/json');
res.json({ "error": "Reauthenticate" });
return;
}
if (!packet.target) {
res.status(400);
res.header("Content-Type", 'application/json');