This repository was archived by the owner on Jul 31, 2025. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathmain.js
More file actions
1088 lines (942 loc) · 39.7 KB
/
Copy pathmain.js
File metadata and controls
1088 lines (942 loc) · 39.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import pool from './db.js';
import imageType from 'image-type';
import fs from 'fs';
import sharp from 'sharp';
import { v4 as uuidv4 } from 'uuid';
import path from 'path';
import { fileURLToPath } from 'url';
import fetch from 'node-fetch';
import session from 'express-session';
import connectPgSimple from 'connect-pg-simple';
import {JSDOM} from 'jsdom';
import { Client, GatewayIntentBits } from 'discord.js';
import ratelimit from 'express-rate-limit';
import helmet from 'helmet';
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.DirectMessages, GatewayIntentBits.GuildMessages] });
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const app = express();
const port = 3000;
// Create a PostgreSQL session store
const pgSession = connectPgSimple(session);
// Allow users that we cant message to need admin to login
const byPassUsers = [{id: 1580038, username: "Лучистоглазик"}];
// Trust proxy
app.set('trust proxy', 1);
// Disable headers
app.use(helmet({
crossOriginResourcePolicy: false
}))
// Set Content Security Policy to allow images from specific sources
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https://avatars.githubusercontent.com"]
}
}));
// No COrs
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST, DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials', 'true'); // Allow credentials
next();
});
// setup sessions
app.use(session({
store: new pgSession({
pool: pool, // Connection pool
tableName: 'user_sessions' // Use a custom table name
}),
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: {
maxAge: 24 * 60 * 60 * 1000, // 24 hours
secure: false, // Set to true if using HTTPS
httpOnly: false,
sameSite: "lax",
},
rolling: true // Reset the cookie Max-Age on every request
}));
app.use(express.json());
app.use('/locale/', express.static(path.join(__dirname, "locale"), { index: false }));
app.use('/images/', express.static(path.join(__dirname, "images"), { index: false }));
app.get('/', async (req, res) => {
// console.log(req.session, "Request from: ", req.ip);
try {
const data = await pool.query("SELECT * FROM costumes");
const playerNums = data.rows.length;
// Read the main.html file
fs.readFile(path.join(__dirname, 'main.html'), 'utf8', (err, htmlContent) => {
if (err) {
console.error("Error reading the HTML file:", err);
return res.status(500).send("Server error");
}
// Replace the placeholder with the actual number of players
htmlContent = htmlContent.replace("%{PlayerNum}%", playerNums);
// Send the modified HTML content
res.send(htmlContent);
});
} catch (err) {
console.error(err);
res.status(500).send("An error occurred");
}
});
app.get("/guidelines", async (req, res) => {
// Read the guidelines.html file
fs.readFile(path.join(__dirname, 'guidelines.html'), 'utf8', (err, htmlContent) => {
if (err) {
console.error("Error reading the HTML file:", err);
return res.status(500).send("Server error");
}
// Send the modified HTML content
res.send(htmlContent);
});
});
app.get("/privacy", async (req, res) => {
// Read the guidelines.html file
fs.readFile(path.join(__dirname, 'privacy.html'), 'utf8', (err, htmlContent) => {
if (err) {
console.error("Error reading the HTML file:", err);
return res.status(500).send("Server error");
}
// Send the modified HTML content
res.send(htmlContent);
});
});
const costumeSubmissionLimiter = ratelimit({
windowMs: 5 * 1000, // 5 seconds
max: 1,
message: "Too many requests, please try again later",
statusCode: 429
});
app.post("/", costumeSubmissionLimiter, async (req, res) => {
const {name, imgdata} = req.body;
// Check if the person has authenticated
if (!req.session.authenticated) {
return res.status(403).send({message: "Unauthorized"});
}
// Check if the person is authenticated under the specified name
if (req.session.user.id !== name) {
return res.status(403).send({message: "Unauthorized"});
}
async function generateUUID(retryCount = 0) {
if (retryCount > 5) {
throw new Error("UUID generation failed after multiple attempts");
}
const uuid = uuidv4();
try {
const pooldata = await pool.query("SELECT * FROM costumes WHERE imguuid = $1", [uuid]);
if (pooldata.rows.length > 0){
return generateUUID(retryCount + 1);
}
return uuid;
}
catch (err){
console.error(err);
return generateUUID(retryCount + 1);
}
}
try {
if (typeof name !== 'number' || name > 9999999999 || name < 0) {
return res.status(400).send({message: "name is not a valid ID"});
}
if (typeof imgdata !== 'string') {
return res.status(400).send({message: "imgdata must be a base64-encoded string"});
}
const buffer = Buffer.from(imgdata, 'base64');
const type = await imageType(buffer);
if (!type || !type.mime || !type.mime.startsWith('image/')) {
return res.status(400).send({message: "imgdata is not an image blob"});
}
const cleanImageBuffer = await sharp(buffer)
.resize(100, 150)
.png()
.toBuffer();
const imguuid = await generateUUID();
// Check if the name already exists in the database
const existingEntry = await pool.query(`
SELECT imguuid FROM costumes WHERE name = $1
`, [name]);
let previousImgUuid = null;
if (existingEntry.rows.length > 0) {
// Store the imguuid of the existing entry
previousImgUuid = existingEntry.rows[0].imguuid;
}
if (!fs.existsSync('./images')) {
fs.mkdirSync('./images');
}
fs.writeFileSync(`./images/${imguuid}.png`, cleanImageBuffer);
await pool.query(`
INSERT INTO costumes (name, imguuid)
VALUES ($1, $2)
ON CONFLICT (name)
DO UPDATE SET imguuid = EXCLUDED.imguuid
`, [name, imguuid]);
// Delete old image file to save my poor disk space.
if (previousImgUuid && previousImgUuid !== imguuid) {
const sanitizedImgUuid = path.basename(previousImgUuid);
const sanitizedImagePath = path.join(__dirname, 'images', `${sanitizedImgUuid}.png`);
if (fs.existsSync(sanitizedImagePath)) {
fs.unlinkSync(sanitizedImagePath);
}
}
res.status(201).send({message: "Successfully added or updated child"});
logger(`Added or updated child with name: ${name} and imguuid: ${imguuid}`, "info");
} catch (err) {
console.error(err);
res.sendStatus(500);
}
});
app.post("/register", async (req, res) => {
let {id, username} = req.body;
logger(`Registering user with ID: ${id} and username: ${username}`, "info");
id = parseInt(id);
if (typeof id !== 'number' || id > 9999999999 || id < 0) {
return res.status(400).send({message: "id is not a valid ID"});
}
async function sendPincode() {
// Create entry of the user in the database with a random 6 digit pin code that expires in 5 minutes
const pinCode = Math.floor(Math.random() * 900000) + 100000;
const expiryTime = new Date(Date.now() + 300000);
try {
// Send Pincode to the user via PM on Catwar
var message = "Привет, " + username + ", [br] ваш проверочный код: [b]" + pinCode + "[/b]. Этот код истечет через 5 минут. [br] Если вы не запрашивали этот код, пожалуйста, проигнорируйте это сообщение.";
var title = "#SaveCW Проверочный код";
logger(`Sending verification code to ${username} with code: ${pinCode}`, "info");
fetch("https://catwar.net/ajax/mess_send", {
"headers": {
"accept": "application/json, text/javascript, */*; q=0.01",
"cache-control": "no-cache",
"content-type": "application/x-www-form-urlencoded; charset=UTF-8",
"cookie": process.env.PM_COOKIES,
"pragma": "no-cache",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
},
"body": `whom=${username}&subject=${title}&text=${message}`,
"method": "POST",
"mode": "cors",
"credentials": "include"
})
.then(x => x.json())
.then(async y => {
const isBypassUser = byPassUsers.some(x => x.id === id || x.username === username);
if (y["fail"] !== undefined && !isBypassUser) {
logger("Error sending verification code: " + y + " for: " + username, "error");
if (y["fail"] === "notFound") {
return res.status(400).send({ message: "User not found" });
}
return res.status(500).send({ message: "Failed to send verification code." });
} else {
if (isBypassUser) {
logger(`Bypassing verification error for ${username}`, "info");
}
// Save the user in the database
await pool.query(`
INSERT INTO users (id, username, pin, expiry_time)
VALUES ($1, $2, $3, $4)
ON CONFLICT (id)
DO UPDATE SET
username = EXCLUDED.username,
pin = EXCLUDED.pin,
expiry_time = EXCLUDED.expiry_time
`, [id, username, pinCode, expiryTime]);
res.status(200).send({message: "Successfully registered user"});
}
})
.catch(err => {
console.error(err);
res.status(500).send({message: "Failed to send verification code."});
});
}
catch (err) {
console.error(err);
res.sendStatus(500);
}
}
// Details sanity check
// https://catwar.net/achievements?id=1606120
fetch(`https://catwar.net/achievements?id=${id}`, {
headers: {
"accept": "text/html",
"accept-language": "en-GB,en;q=0.9,el;q=0.8,en-US;q=0.7",
"cache-control": "max-age=0",
"cookie": process.env.PM_COOKIES,
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1"
},
"method": "GET",
"mode": "cors",
"credentials": "include"
})
// Create dom from the response
.then(x => x.text())
.then(y => {
// Create dom from response
const dom = new JSDOM(y);
// Find a tag with src catid and get the value
// console.log(y);
let catid = dom.window.document.querySelector(`a[href='/cat${id}']`);
if (!catid) {
return res.status(400).send({message: "User not found"});
}
catid = catid.textContent;
// Replace spaces on catid with html spaces %20
catid = catid.trim().replaceAll(" ", "%20");
if (catid !== username) {
return res.status(403).send({message: "Information does not match"});
}
else {
// Check That they are not a bot or admin
fetch(`https://catwar.net/cat${id}`, {
headers: {
"accept": "text/html",
"accept-language": "en-GB,en;q=0.9,el;q=0.8,en-US;q=0.7",
"cache-control": "max-age=0",
"cookie": process.env.PM_COOKIES,
"sec-fetch-dest": "document",
"sec-fetch-mode": "navigate",
"sec-fetch-site": "same-origin",
"sec-fetch-user": "?1",
"upgrade-insecure-requests": "1"
},
"method": "GET",
"mode": "cors",
"credentials": "include"
})
.then(e => e.text())
.then(f => {
// Create dom from response
const dom = new JSDOM(f);
let admin = dom.window.document.querySelector(`p[data-cat='${id}']`).textContent.includes("!кизалготсичуЛ");
if (admin) {
logger(`CatWar Staff register attempt canceled: User ID ${id}, Username ${username}.`, "info");
return res.status(401).send({message: "Unauthorized"});
}
else {
sendPincode();
}
})
}
})
.catch(err => {
console.error(err);
return res.status(500).send({message: "Failed to verify user"});
});
});
app.post("/verify", async (req, res) => {
let {id, code} = req.body;
id = parseInt(id);
code = parseInt(code);
if (typeof id !== 'number' || id > 9999999999 || id < 0) {
return res.status(401).send({message: "id is not a valid ID"});
}
if (typeof code !== 'number' || code > 999999 || code < 100000) {
return res.status(401).send({message: "pincode is not a valid 6 digit code"});
}
try {
const data = await pool.query("SELECT * FROM users WHERE id = $1", [id]);
if (data.rows.length === 0) {
return res.status(404).send({message: "User not found"});
}
const user = data.rows[0];
if (user.expiry_time < new Date()) {
return res.status(400).send({message: "Pincode has expired"});
}
if (user.pin !== code) {
// Add to the tries count and lock the user out after 5 tries
await pool.query("UPDATE users SET tries = tries + 1 WHERE id = $1", [id]);
const tries = await pool.query("SELECT tries FROM users WHERE id = $1", [id]);
if (tries.rows[0].tries >= 5) {
await pool.query("UPDATE users SET pin = NULL, expiry_time = NULL, tries = 0 WHERE id = $1", [id]);
return res.status(400).send({message: "Too many incorrect pincode attempts. Please try again."});
}
else {
return res.status(403).send({message: "Incorrect pincode"});
}
}
// Remove the passcode from the database
await pool.query("UPDATE users SET pin = NULL, expiry_time = NULL WHERE id = $1", [id]);
// Save unique session ID
req.session.authenticated = true;
req.session.user = {id: id, username: user.username};
// Return with sessionID
res.status(200).send({message: "Successfully verified user", sessionID: req.sessionID});
logger(`User with ID: ${id} and username: ${user.username} has been successfully verified`, "info");
}
catch (err) {
console.error(err);
res.sendStatus(500);
}
});
app.get("/search", async (req, res) => {
const {name} = req.query;
// Check if name is a number by trying to convert it to a number
const nameInt = parseInt(name);
if (isNaN(nameInt) || nameInt > 9999999999 || nameInt < 0) {
return res.status(400).send({message: "name is not a valid ID"});
}
try {
const data = await pool.query("SELECT * FROM costumes WHERE name = $1", [nameInt]);
res.status(200).send({children: data.rows});
} catch (err){
console.error(err);
res.sendStatus(500);
}
})
app.delete("/delete/:name", async (req, res) => {
const name = req.params.name;
// Check if name is a number by trying to convert it to a number
const nameInt = parseInt(name);
if (isNaN(nameInt) || nameInt > 9999999999 || nameInt < 0) {
return res.status(400).send({message: "name is not a valid ID"});
}
// Check if the person has authenticated
if (!req.session.authenticated) {
return res.status(403).send({message: "Unauthorized"});
}
// Check if the person is authenticated under the specified name
if (req.session.user.id !== nameInt) {
return res.status(403).send({message: "Unauthorized"});
}
// Check if person is in the database
const data = await pool.query("SELECT * FROM costumes WHERE name = $1", [nameInt]);
if (data.rows.length === 0) {
return res.status(404).send({message: "Not Found"});
}
try {
await pool.query("DELETE FROM costumes WHERE name = $1", [nameInt]);
res.sendStatus(200);
logger(`Deleted child with name: ${nameInt} and imguuid: ${data.rows[0].imguuid}`, "info");
}
catch (err) {
console.error(err);
res.sendStatus(500);
}
});
app.get("/admin/login", async (req, res) => {
if (!req.session.isAdmin || !req.session.discordID){
const url = `https://discord.com/oauth2/authorize?client_id=${process.env.DC_CLIENT_ID}&response_type=code&redirect_uri=https%3A%2F%2Fcat.arisamiga.rocks%2Fapi%2Fauth%2Fdiscord%2Fredirect&scope=identify`
// Create button to redirect to discord login
const button = `<a href=${url}><button>Login with Discord</button></a>`
res.send(button);
}
else {
// Double Check
if (!req.session.isAdmin || req.session.discordID != process.env.DC_ID){
return res.redirect(process.env.WEBSITE_URL)
}
// Send alert on discord on pm to DC_ID
client.users.fetch(process.env.DC_ID).then(user => {
// Make a embed with details of who logged in
const embed = {
color: 0xffc223,
title: 'Admin Login',
description: `
Admin ${user.username} has logged in.
\n ID: \`${req.session.discordID}\`
\n Admin: \`${req.session.isAdmin}\`
\n Session ID: \`${req.sessionID}\`
\n IP: \`${req.headers['x-forwarded-for'] || req.socket.remoteAddress}\`
\n User Agent: \`${req.headers['user-agent']}\`
\n Language: \`${req.headers['accept-language']}\`
\n OS: \`${req.headers['user-agent'].split(") ")[0].split("; ")[1]}\`
\n Time: ${new Date()}
`,
timestamp: new Date(),
footer: {
text: 'Costume Server Admin Panel',
},
}
// Send the embed to the DC_ID
user.send({embeds: [embed]});
logger(`Admin with ID: ${req.session.discordID} has logged in`, "info");
})
.catch(err => {
logger(`Admin with ID: ${req.session.discordID} has logged in but error occured canceling..`, "info");
return;
});
// Query the database for costumes
let costumesData = await pool.query("SELECT * FROM costumes");
// Initialize the HTML structure
let table = `
<html>
<head>
<head>
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
margin-top: 1rem;
flex-direction: column;
}
table {
width: 80%;
margin: 20px auto;
border-collapse: collapse;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}
th, td {
padding: 12px 15px;
border: 1px solid #ddd;
text-align: center;
}
th {
background-color: #f4f4f4;
font-weight: bold;
}
tr:nth-child(even) {
background-color: #f9f9f9;
}
tr:hover {
background-color: #f1f1f1;
}
.one h1 {
text-align: center;
padding-bottom: 5px;
}
.one h1:before {
width: 28px;
height: 5px;
display: block;
content: "";
position: fixed;
bottom: 3px;
left: 50%;
margin-left: -14px;
background-color: #b80000;
}
.one h1:after {
width: 100px;
height: 1px;
display: block;
content: "";
position: relative;
margin-top: 25px;
left: 50%;
margin-left: -50px;
background-color: #b80000;
}
.dangerButton {
background-color: #f44336;
color: white;
padding: 10px 15px;
border: none;
border-radius: 5px;
cursor: pointer;
}
.left {
position: absolute;
top: 10;
left: 10;
width: 100px;
}
textarea {
width: 80%;
margin: 20px auto;
border: 1px solid #ccc; /* Light gray border */
border-radius: 5px; /* Rounded corners */
padding: 10px; /* Padding for better readability */
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); /* Subtle shadow */
resize: none; /* Disable resizing */
background-color: #f9f9f9; /* Light background color */
font-family: 'Courier New', Courier, monospace; /* Monospaced font */
color: #333; /* Dark text color */
overflow: auto; /* Enable scrolling if content overflows */
}
</style>
<title>Admin Panel - Costume Server</title>
<link rel="icon" href="https://avatars.githubusercontent.com/u/172896885">
</head>
<body>
<img src="https://avatars.githubusercontent.com/u/172896885" class="left">
<div class="one">
<h1>Admin Page</h1>
</div>
<h1>Costumes</h1>
<table>
`;
// Populate the table with costumes data
for (const row of costumesData.rows) {
table += `
<tr>
<td><b>ID: </b><a href="https://catwar.net/cat${row.name}">${row.name}</a></td>
<td><b>UUID: </b>${row.imguuid}</td>
<td><img src="${process.env.WEBSITE_URL}/images/${row.imguuid}.png"></td>
<td><button id="delCostume" class="dangerButton">🗡️🕶️ Deal with Costume..</button></td>
</tr>
`;
}
table += "</table>";
// Query the database for users
let usersData = await pool.query("SELECT * FROM users");
// Add users data to the table
table += `
<br>
<hr>
<br>
<h1>Users</h1>
<table>
`;
for (const row of usersData.rows) {
table += `
<tr>
<td><b>ID: </b><a href="https://catwar.net/cat${row.id}">${row.id}</a></td>
<td><b>Username: </b>${row.username}</td>
<td><b>Pin: </b>${row.pin}</td>
<td><b>Expiry Time: </b>${row.expiry_time}</td>
<td><b>Tries: </b>${row.tries}</td>
<td><button id="delUser" class="dangerButton">🚪 Let the user go...</button></td>
</tr>
`;
}
table += `
</table>
<br>
<hr>
<br>
<h1>Sessions</h1>
<table>
`
let sessionData = await pool.query("SELECT * FROM user_sessions");
for (const row of sessionData.rows) {
table += `
<tr>
<td><b>Session ID: </b>${row.sid}</td>
<td><b>Session Data: </b>${JSON.stringify(row.sess)}</td>
<td><b>Expiry Time: </b>${row.expire}</td>
<td><button id="delSession" class="dangerButton">💥 Destroy Session...</button></td>
</tr>
`;
}
table +=`
</table>
<br>
<hr>
<br>
<h1>Logs</h1>
<textarea rows="10" cols="50" readonly>`
// Read the log file and add it to the textarea
table += fs.readFileSync("log.log", "utf8").toString().replace(/^[ \t]+/gm, '').replace(/^\s*[\r\n]/gm, '');
table += "</textarea>";
// Script for fetches
table += `
<script>
document.querySelectorAll("#delSession").forEach((button) => {
button.addEventListener("click", async () => {
const sessionID = button.parentElement.parentElement.querySelector("td").textContent.split(": ")[1];
await fetch("${process.env.WEBSITE_URL}/api/admin/session/destroy", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({sessionID})
});
location.reload();
});
});
document.querySelectorAll("#delCostume").forEach((button) => {
button.addEventListener("click", async () => {
const imguuid = button.parentElement.parentElement.querySelector("td:nth-child(2)").textContent.split(": ")[1];
await fetch("${process.env.WEBSITE_URL}/api/admin/costume/delete", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({imguuid})
});
location.reload();
});
});
document.querySelectorAll("#delUser").forEach((button) => {
button.addEventListener("click", async () => {
const id = button.parentElement.parentElement.querySelector("td:nth-child(1)").textContent.split(": ")[1];
await fetch("${process.env.WEBSITE_URL}/api/admin/user/delete", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({id})
});
location.reload();
});
});
</script>
`
table += "</body></html>";
// Send the constructed HTML as the response
res.send(table);
}
});
app.post("/api/admin/session/destroy", async (req, res) => {
const {sessionID} = req.body;
if (!sessionID) {
return res.status(400).send({message: "No session ID provided"});
}
// Double Check
if (!req.session.isAdmin || req.session.discordID != process.env.DC_ID){
return res.redirect(process.env.WEBSITE_URL)
}
try {
// Send alert on discord on pm to DC_ID
client.users.fetch(process.env.DC_ID).then(async user => {
// Make a embed with details of who logged in
const sessionData = await pool.query("SELECT * FROM user_sessions WHERE sid = $1", [sessionID]);
const embed = {
color: 0xe43e30,
title: 'Admin: 💥 Session Destroyed',
description: `
Admin destroyed session with ID: \`${sessionID}\`
\n Session Data: \`${JSON.stringify(sessionData.rows[0].sess)}\`
\n Expiry Time: \`${sessionData.rows[0].expire}\`
---------------------------------------------------
\n ID: \`${req.session.discordID}\`
\n Admin: \`${req.session.isAdmin}\`
\n Session ID: \`${req.sessionID}\`
\n IP: \`${req.headers['x-forwarded-for'] || req.socket.remoteAddress}\`
\n User Agent: \`${req.headers['user-agent']}\`
\n Language: \`${req.headers['accept-language']}\`
\n OS: \`${req.headers['user-agent'].split(") ")[0].split("; ")[1]}\`
\n Time: ${new Date()}
`,
timestamp: new Date(),
footer: {
text: 'Costume Server Admin Panel',
},
}
// Send the embed to the DC_ID
user.send({embeds: [embed]});
logger(`Admin with ID: ${req.session.discordID} destroyed session with ID: ${sessionID}`, "info");
await pool.query("DELETE FROM user_sessions WHERE sid = $1", [sessionID]);
res.sendStatus(200);
})
.catch(err => {
logger(`Admin with ID: ${req.session.discordID} tried to destroy session with ID: ${sessionID} but it was not found`, "info");
res.sendStatus(500);
});
} catch (err) {
console.error(err);
res.sendStatus(500);
}
});
app.post("/api/admin/costume/delete", async (req, res) => {
const {imguuid} = req.body;
if (!imguuid) {
return res.status(400).send({message: "No imguuid provided"});
}
// Double Check
if (!req.session.isAdmin || req.session.discordID != process.env.DC_ID){
return res.redirect(process.env.WEBSITE_URL)
}
// Send alert on discord on pm to DC_ID
client.users.fetch(process.env.DC_ID).then(async user => {
const costumeData = await pool.query("SELECT * FROM costumes WHERE imguuid = $1", [imguuid]);
if (costumeData.rows.length === 0) {
logger(`Admin with ID: ${req.session.discordID} tried to delete costume with UUID: ${imguuid} but it was not found`, "info");
return res.status(404).send({message: "Costume not found"});
}
const embed = {
color: 0xe43e30,
title: 'Admin: 🗡️🕶️ Dealt with Costume',
description: `
Admin deleted costume with UUID: \`${imguuid}\`
\n Costume Name: \`${costumeData.rows[0].name}\`
\n Costume ID: \`${costumeData.rows[0].id}\`
---------------------------------------------------
\n ID: \`${req.session.discordID}\`
\n Admin: \`${req.session.isAdmin}\`
\n Session ID: \`${req.sessionID}\`
\n IP: \`${req.headers['x-forwarded-for'] || req.socket.remoteAddress}\`
\n User Agent: \`${req.headers['user-agent']}\`
\n Language: \`${req.headers['accept-language']}\`
\n OS: \`${req.headers['user-agent'].split(") ")[0].split("; ")[1]}\`
\n Time: ${new Date()}
`,
timestamp: new Date(),
footer: {
text: 'Costume Server Admin Panel',
},
}
// Send the embed to the DC_ID
user.send({embeds: [embed]});
logger(`Admin with ID: ${req.session.discordID} deleted costume with UUID: ${imguuid}`, "info");
try {
await pool.query("DELETE FROM costumes WHERE imguuid = $1", [imguuid]);
// Sanitize the input to prevent path traversal
const sanitizedImgUuid = path.basename(imguuid);
const filePath = path.join(__dirname, 'images', `${sanitizedImgUuid}.png`);
if (fs.existsSync(filePath)) {
fs.unlinkSync(filePath);
}
res.sendStatus(200);
} catch (err) {
console.error(err);
res.sendStatus(500);
}
})
.catch(err => {
logger(`Admin with ID: ${req.session.discordID} tried to delete costume with UUID: ${imguuid} but it was not found`, "info");
res.sendStatus(500);
});
});
app.post("/api/admin/user/delete", async (req, res) => {
const {id} = req.body;
if (!id) {
return res.status(400).send({message: "No id provided"});
}
// Double Check
if (!req.session.isAdmin || req.session.discordID != process.env.DC_ID){
return res.redirect(process.env.WEBSITE_URL)
}
// Send alert on discord on pm to DC_ID
client.users.fetch(process.env.DC_ID).then(async user => {
const userData = await pool.query("SELECT * FROM users WHERE id = $1", [id]);
const embed = {
color: 0xe43e30,
title: 'Admin: 🚪 Let the User Go',
description: `
Admin deleted user with ID: \`${id}\`
\n Username: \`${userData.rows[0].username}\`
\n Pin: \`${userData.rows[0].pin}\`
\n Expiry Time: \`${userData.rows[0].expiry_time}\`
\n Tries: \`${userData.rows[0].tries}\`
---------------------------------------------------
\n ID: \`${req.session.discordID}\`
\n Admin: \`${req.session.isAdmin}\`
\n Session ID: \`${req.sessionID}\`
\n IP: \`${req.headers['x-forwarded-for'] || req.socket.remoteAddress}\`
\n User Agent: \`${req.headers['user-agent']}\`
\n Language: \`${req.headers['accept-language']}\`
\n OS: \`${req.headers['user-agent'].split(") ")[0].split("; ")[1]}\`
\n Time: ${new Date()}
`,
timestamp: new Date(),
footer: {
text: 'Costume Server Admin Panel',
},
}
// Send the embed to the DC_ID
user.send({embeds: [embed]});
logger(`Admin with ID: ${req.session.discordID} deleted user with ID: ${id}`, "info");
try {
await pool.query("DELETE FROM users WHERE id = $1", [id]);
res.sendStatus(200);
} catch (err) {
console.error(err);
res.sendStatus(500);
}
})
.catch(err => {
logger(`Admin with ID: ${req.session.discordID} tried to delete user with ID: ${id} but it was not found`, "info");
res.sendStatus(500);
});
});
app.get("/api/auth/discord/redirect", async (req, res) => {
const { code } = req.query;
if (!code) {
return res.status(400).send({ message: "No code provided" });
}
const params = new URLSearchParams({
client_id: process.env.DC_CLIENT_ID,
client_secret: process.env.DC_CLIENT_SECRET,
grant_type: "authorization_code",
code: code,
redirect_uri: `${process.env.WEBSITE_URL}/api/auth/discord/redirect`,
scope: "identify"
})
fetch("https://discord.com/api/oauth2/token", {
method: "POST",
body: params,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
})
.then(x => x.json())