Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
1807 lines (1554 loc) · 61.8 KB
/
Copy pathapp.js
File metadata and controls
1807 lines (1554 loc) · 61.8 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
//AMPLink Main File
//Made by sam
// Welcome to the main file. It is not recommended to edit any values here,
// unless you know what you are doing.
// The main file defines all the pages, as well as all the server-side actions, as well as calling actions from the TorchRemote API.
//Modules
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const bcrypt = require('bcrypt');
const RateLimit = require('express-rate-limit');
const e = require('express');
const fs = require('fs')
const { jsonrepair } = require('jsonrepair')
const WebSocket = require('ws')
var jp = require('jsonpath');
var JSONbig = require('json-bigint');
var sqlEscape = require('sql-escape');
var randomstring = require("randomstring");
const fileUpload = require('express-fileupload');
const path = require('path');
const multer = require('multer');
const upload = multer({ dest: 'temp/' });
var moment = require('moment');
//Config
require('dotenv').config()
//Local Files
// Internal
const notify = require("./functions/notify.js");
const getInstalledPlugins = require('./functions/getInstalledPlugins.js');
const getRootKeys = require('./functions/getRootKeys.js');
const truncate = require("./functions/truncate.js")
//steam
const getSteamPlayerSummaries = require('./functions/steam/getSteamPlayerSummaries.js');
//chat
const postInvokeCommand = require('./functions/chat/postInvokeCommand.js')
const postSendChatMessage = require('./functions/chat/postSendChatMessage.js')
//logs
const websocketChat = require('./functions/logs/websocketChat.js')
const websocketLogs = require('./functions/logs/websocketLogs.js')
//plugins
const deletePlugin = require('./functions/plugins/deletePlugin.js')
const getAllPlugins = require('./functions/plugins/getAllPlugins.js')
const putPlugin = require('./functions/plugins/putPlugin.js')
//plugins download
const getPluginsDownloadsAll = require('./functions/plugins/downloads/getPluginsDownloadsAll.js')
const postPluginsDownload = require("./functions/plugins/downloads/postPluginsDownload.js")
//server
const getHeartbeat = require('./functions/server/getHeartbeat.js');
const getSettings = require('./functions/server/getSettings.js');
const getStatus = require('./functions/server/getStatus.js');
const postSettings = require('./functions/server/postSettings.js');
const postStart = require('./functions/server/postStart.js');
const postStop = require('./functions/server/postStop.js');
const getAllPlayers = require('./functions/players/getAllPlayers.js');
const getAllBannedPlayers = require('./functions/players/getAllBannedPlayers.js')
const postBanPlayer = require('./functions/players/postBanPlayer.js');
const postKickPlayer = require('./functions/players/postKickPlayer.js');
const postPromotePlayer = require('./functions/players/postPromotePlayer.js');
const postDemotePlayer = require('./functions/players/postDemotePlayer.js');
const postDisconnectPlayer = require('./functions/players/postDisconnectPlayer.js');
const postUnbanPlayer = require('./functions/players/postUnbanPlayer.js');
//settings
const getTorchValues = require("./functions/settings/getTorchValues.js");
const getTorchSchema = require("./functions/settings/getTorchSchema.js");
const getTorchSettings = require("./functions/settings/getTorchSettings.js");
const patchTorchValues = require("./functions/settings/patchTorchValues.js");
//grids
const getAllGrids = require("./functions/grids/getAllGrids.js");
const deleteGridId = require("./functions/grids/deleteGridId.js");
const { randomInt } = require('crypto');
const { json } = require('stream/consumers');
const { platform } = require('os');
const { del } = require('request');
require("./functions/updater.js")
require('./functions/autoRestartInterval.js')
//updater.update()
notify.notify(1,"Starting AMPLink...")
try {
const connection = require('./db.js');
connection.connect((error) => {
if (error) {
notify.notify(4, `Database connection error: ${error}`)
} else {
notify.notify(1, "Successfully connected to SQLite Database.")
}
});
// Set up the Express app
const app = express();
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(bodyParser.json());
app.use(fileUpload());
//Randomize some letters to make key
var token = randomstring.generate();
if (process.env.USE_AMP_TOKEN == 'true') {
notify.notify(2,"USE_AMP_TOKEN = true")
var token = process.env.AMP_SESSION_TOKEN;
} else {
}
//notify.notify(3,token)
app.use(session({
secret: token,
resave: false,
saveUninitialized: true,
cookie: { secure: false, sameSite: 'lax' }
}));
const limiter = RateLimit({
windowMs: 60 * 1000, //Limit length
max: process.env.AMP_LOGIN_RATELIMIT, // limit each IP to 5 requests per windowMs
delayMs: 0, // disable delaying - full speed until the max limit is reached
message: `
<!doctype html> <html> <head> <meta charset="utf-8"> <title>AMPLink Control Panel</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous"> <link href="style.css" rel="stylesheet" type="text/css"> <style>body{text-align: center; overflow-y: hidden; margin: 0px;}main{margin: 0px;}.aligntocenter{text-align: left; width: 50vw;}.center{text-align: center;}@media (max-width:600px){.aligntocenter{width: 75vw;}}@media (prefers-color-scheme: dark){.bg-adapt{background-color: #333333;}.bg-adapt-txt{background-color: #4e4e4e; border: none;}}@media (prefers-color-scheme: light){.bg-adapt{background-color: #EEEEEE; color: #000000;}.bg-adapt-txt{background-color: #ffffff; color: #000000;}}}</style> </head> <body> <main> <div class="container mt-4 aligntocenter"> <h1 class="alert center"><b>AMPLink</b></h1> <div class="card bg-adapt"> <div class="card-header center">Login</div><div class="card-body"> <form action="/login" method="POST"> <div class="mb-3"> <label for="username" class="form-label">Username:</label><br><input type="text" class="form-control bg-adapt-txt" disabled> <label for="password" class="form-label">Password:</label><br><input type="password" class="form-control bg-adapt-txt" disabled> </div><button class="btn btn-primary" disabled>Submit</button> <div style="padding: 3px; float: right; max-width:150px; text-align: center; position: relative; top:10px; z-index:1111;"> <em>AMPLink v0.3-beta Build</em> </div></form> </div><div style="margin: 5px;"> <p class="callout-danger">Too many login attempts. Please try again in one minute.</p></div></div></div></main> </body> </html>
` // custom error message
});
const embeddedLimiter = RateLimit({
windowMs: 60 * 1000, //Limit length
max: process.env.AMP_EMBEDDED_RATELIMIT, // limit each IP to x requests per windowMs
delayMs: 0, // disable delaying - full speed until the max limit is reached
message: `
<p class="callout-danger col-md-11">Error: You are sending too many requests.</p>
` // custom error message
});
const consoleLimiter = RateLimit({
windowMs: 60 * 1000, //Limit length
max: process.env.AMP_CLIENT_RATELIMIT, // limit each IP to 120 requests. This equates to 2 AMPLink instances per IP.
delayMs: 0, // disable delaying - full speed until the max limit is reached
message: `
<p class="callout-danger col-md-11">Error: You are sending too many requests.</p>
` // custom error message
});
//initialize Express.JS
app.use(express.static(__dirname + '/views'));
//Set view engine
app.set('view engine', 'hbs');
app.set('trust proxy', 1);
//call websocket console manager to start logging
async function startWebsocketManager() {
websocketLogs.websocketLogs()
}
//call websocket console manager to start logging
async function startWebsocketChatManager() {
websocketChat.websocketChat()
}
//Prevent sql attack
function escapeMiddleware(req, res, next) {
for (let key in req.body) {
req.body[key] = sqlEscape(req.body[key]);
}
next();
}
// Set up the routes
//Homepage
app.get('/', (req, res) => {
// Check if the user is logged in
if (req.session.userId) {
// The user is logged in
// Get the username of the logged-in user
const query = `SELECT username FROM users WHERE id = ?`;
connection.query(query, [req.session.userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.render('error.hbs', {message: 'A 500 error has occured. Please try again.',error})
} else {
/*setInterval(() => {
(async () => {
var res = (await getStatus.getStatus());
JSON.stringify(res)
//console.log(res)
return res
})();
}, 5000); // Update every 5 seconds*/
res.render("home.hbs", {message: req.session.username})
}
});
} else {
// The user is not logged in
res.render("login.hbs")
}
});
app.get("/register", escapeMiddleware, (req, res) => {
res.render("register.hbs")
})
/*app.get('/legacylogin', escapeMiddleware, (req, res) => {
// Render the login form
res.send(`
<h1>Login to AMPLink</h1>
<form action="/login" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br><br>
<input type="submit" value="Submit">
</form>
`);
});*/
app.get('/login'), (req, res) => {
res.render("login.hbs")
}
app.post('/login', limiter, escapeMiddleware, (req, res) => {
const { username, password } = req.body;
// Is user in database?
const query = `SELECT * FROM users WHERE username = ?`;
connection.query(query, [username], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.render('error.hbs', {message: 'A 500 server-side error has occured. Check if the database is running correctly, and try again.',error})
} else if (results.length === 0) {
res.render('login.hbs', {message: 'Invalid password. Please try again.'})
} else {
// Get the hashed password from the database
const hashedPassword = results[0].password;
// Compare password with hashed one using bcrypt
bcrypt.compare(password, hashedPassword, (error, result) => {
if (error) {
notify.notify(3, `Bycrypt error:', ${error}`)
res.render('error.hbs', {message: 'A 500 error has occured. Please try again.',error})
} else if (result) {
// Save the user ID in the session
req.session.userId = results[0].id;
res.render('home.hbs', {message: results[0].username})
} else {
res.render('login.hbs', {message: 'Invalid password. Please try again.'})
}
});
}
});
});
app.post('/register', embeddedLimiter, escapeMiddleware, (req, res) => {
// Ensure passwords match
if (req.session.userId) {
const { username, password, confirmPassword } = req.body;
if (password !== confirmPassword) {
res.render('register.hbs', {message: 'Ensure the passwords match, and try again.'})
} else {
// Check if the username is already taken
const query = `SELECT * FROM users WHERE username = ?`;
connection.query(query, [username], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.render('error.hbs', {message: 'A 500 error has occured. Please try again.',error})
} else if (results.length > 0) {
res.render('register.hbs', {message: 'Username already taken.'})
} else {
// Hash the password using bcrypt
bcrypt.hash(password, 10, (error, hashedPassword) => {
if (error) {
notify.notify(3, `Bycrypt error:', ${error}`)
res.render('register.hbs', {message: 'An error has occured. Please try again later.',error})
} else {
// Insert the new user into the database
const insertQuery = `INSERT INTO users (username, password) VALUES (?, ?)`;
connection.query(insertQuery, [username, hashedPassword], (error) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.render('error.hbs', {message: 'A 500 error has occured. Please try again.',error})
} else {
// The user was successfully registered
res.render('register.hbs', {message: 'User successfully registered. You may now login to the user.'})
}
});
}
});
}
});
}
} else {
res.render('login.hbs');
}
});
app.get('/logout', (req, res) => {
req.session.destroy((error) => {
if (error) {
notify.notify(3, `Session error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else {
res.render('login.hbs', {message: 'You have successfully logged out.'});
}
});
});
app.get('/restricted', (req, res) => {
if (req.session.userId) {
res.send('This is a restricted page.');
} else {
res.render('login.hbs');
}
});
app.get('/login', (req, res) => {
if (req.session.userId) {
res.render('home.hbs');
} else {
res.render('login.hbs');
}
});
app.get('/console', (req, res) => {
if (req.session.userId) {
res.render("console.hbs")
} else {
res.render('login.hbs');
}
});
app.get('/console/logs', consoleLimiter, (req, res) => {
if (req.session.userId) {
fs.readFile('logs.html', 'utf-8', (err, data) => {
if (err) {notify.notify(3,err);}
//console.log(data)
res.send(data)
});
} else {
res.send('<p style="color:#ff4848;"><strong>[AMPLink Websockets Manager]: Invalid session. Please log into AMPLink to resume logging.<strong></p>')
}
});
app.get('/console/chat', consoleLimiter, (req, res) => {
if (req.session.userId) {
fs.readFile('chat.html', 'utf-8', (err, data) => {
if (err) {notify.notify(3,err);}
//console.log(data)
res.send(data)
});
} else {
res.send('<p style="color:#ff4848;"><strong>[AMPLink Websockets Manager]: Invalid session. Please log into AMPLink to resume logging.<strong></p>')
}
});
app.get('/api/status', consoleLimiter, async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'unauthorized' });
try {
var raw = await getStatus.getStatus();
if (raw == 500) return res.json({ online: false });
var parsed = JSON.parse(raw);
res.json({ online: true, status: parsed.status, simSpeed: parsed.simSpeed, uptime: parsed.uptime, memberCount: parsed.memberCount });
} catch(e) {
res.json({ online: false });
}
});
app.post('/panel/players/heal/:name', async (req, res) => {
if (!req.session.userId) return res.status(401).json({ error: 'unauthorized' });
const name = req.params.name;
try {
await postInvokeCommand.postInvokeCommand(`!heal ${name}`);
notify.notify(1, `Heal sent for player ${name}`);
if (req.headers['x-requested-with'] === 'XMLHttpRequest') return res.json({ ok: true });
res.redirect('/players');
} catch(e) {
notify.notify(3, e);
res.redirect('/players');
}
});
app.get('/server/status', consoleLimiter, async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var status = await getStatus.getStatus();
if (status == 500) {
res.send(`Server is offline.`);
} else {
var parsed = JSON.parse(status)
//console.log(parsed)
var serverstatus = JSON.stringify(parsed.status);
var serverSimSpeed = JSON.stringify(parsed.simSpeed);
var serverUptime = JSON.stringify(parsed.uptime);
var serverMemberCount = JSON.stringify(parsed.memberCount);
/*Status Checker
if (serverstatus == 0) {
return serverstatus == "Stopped";
} else if (serverstatus == 1) {
return serverstatus == "Starting";
} else if (serverstatus == 2) {
return serverstatus == "Running";
} else if (serverstatus == 3) {
return serverstatus == "Crashed";
}*/
//console.log(serverstatus)
res.render('status.hbs', {status: serverstatus, sim: serverSimSpeed, uptime: serverUptime, memberCount: serverMemberCount});
}
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.get('/about', (req, res) => {
if (req.session.userId) {
res.render("about.hbs")
} else {
res.render('login.hbs');
}
});
/*=============================
AMP LINK
USER CONTROL
============================*/
app.get('/users', (req, res) => {
if (!req.session.userId) {
res.render('login.hbs');
return;
}
const userId = req.session.userId;
// Check if the user is a superuser
const query = `SELECT is_superuser FROM users WHERE id = ?`;
connection.query(query, [userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.render('error.hbs', {message: results[0].username, errormsg: 'A 500 server error has occured.', error});
} else if (results[0].is_superuser === 1) {
// If the user is a superuser, query the database to get a list of all users.
const query = `SELECT * FROM users`;
connection.query(query, (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.render('error.hbs', {message: results[0].username, errormsg: 'A 500 server error has occured.', error});
} else {
//console.log(results)
res.render('users.hbs', { users: results });
}
});
} else {
// Deny message
res.render('error.hbs', {message: results[0].username, errormsg: 'Only superusers are allowed to access this page. Please contact your Administator if this is an error.'});
}
});
});
app.post('/users/delete/:id', embeddedLimiter, (req, res) => {
if (!req.session.userId) {
res.render('login.hbs');
return;
}
const userId = req.session.userId;
const userToDeleteId = req.params.id;
// Check if the user is a superuser
const query = `SELECT is_superuser FROM users WHERE id = ?`;
connection.query(query, [userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else if (results[0].is_superuser === 1) {
// Delete the user from the database
const query = `DELETE FROM users WHERE id = ?`;
connection.query(query, [userToDeleteId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else {
notify.notify(1, `User with ID of ${userToDeleteId} has been sucessfully deleted. \n${results}`)
// I am extremely lazy, so Ima just copy and paste html here lol
res.send(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AMPLink Control Panel</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<main>
<div class="content">
<h2>User with ID of ${userToDeleteId} has been deleted.</h2>
<p><form action="/users" ><input type="submit" value="Go back" class="btn btn-primary" style="float:left; margin-right: 10px;" ></form></p>
</div>
</main>
</body>
</html>
`);
}
});
} else {
// The user is not a superuser
res.send('You do not have permission to access this page.');
}
});
});
//PromoteUser
app.post('/users/promote/:id', embeddedLimiter, (req, res) => {
if (!req.session.userId) {
res.render('login.hbs');
return;
}
const userId = req.session.userId;
const userToDeleteId = req.params.id;
// Check if the user is a superuser
const query = `SELECT is_superuser FROM users WHERE id = ?`;
connection.query(query, [userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else if (results[0].is_superuser === 1) {
const userId = req.params.id;
// Update the is_superuser column for the user with the given ID
const query = `UPDATE users SET is_superuser = 1 WHERE id = ?`;
connection.query(query, [userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else {
res.send(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AMPLink Control Panel</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<main>
<div class="content">
<h2>User with ID of ${userToDeleteId} has been promoted to a superuser.</h2>
<p><form action="/users" ><input type="submit" value="Go back" class="btn btn-primary" style="float:left; margin-right: 10px;" ></form></p>
</div>
</main>
</body>
</html>
`);
}
});
} else {
// The user is not a superuser
res.send('You do not have permission to access this page.');
}
});
});
//demoteuser
app.post('/users/demote/:id', embeddedLimiter, (req, res) => {
if (!req.session.userId) {
res.render('login.hbs');
return;
}
const userId = req.session.userId;
const userToDeleteId = req.params.id;
// Check if the user is a superuser
const query = `SELECT is_superuser FROM users WHERE id = ?`;
connection.query(query, [userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else if (results[0].is_superuser === 1) {
const userId = req.params.id;
// Update the is_superuser column for the user with the given ID
const query = `UPDATE users SET is_superuser = 0 WHERE id = ?`;
connection.query(query, [userId], (error, results) => {
if (error) {
notify.notify(3, `MySQL query error:', ${error}`)
res.send('An error occurred. Please try again later.');
} else {
res.send(`
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>AMPLink Control Panel</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<main>
<div class="content">
<h2>User with ID of ${userToDeleteId} has been demoted to a user.</h2>
<p><form action="/users" ><input type="submit" value="Go back" class="btn btn-primary" style="float:left; margin-right: 10px;" ></form></p>
</div>
</main>
</body>
</html>
`);
}
});
} else {
// The user is not a superuser
res.send('You do not have permission to access this page.');
}
});
});
/*=============================
AMP LINK
SERVER ACTIONS
============================*/
app.post('/invokeCommand', async (req, res) => {
if (req.session.userId) {
const command = req.body.command || '';
fs.appendFile('./logs.html', `<span style="color:#00ff99;"><b>00:00:00.0000 Server: </b>Running command: !${command}</span><br>`, (err) => {
if (err) notify.notify(3, err);
});
var status = (await postInvokeCommand.postInvokeCommand(command));
const cmdOk = status == 200;
if (req.headers['x-requested-with'] === 'XMLHttpRequest') {
return res.json({ ok: cmdOk, status });
}
if (status == 503) {
res.render('console.hbs', {errormsg: 'Error: Server is offline.'});
} else if (!cmdOk) {
res.render('console.hbs', {errormsg: `Command failed (${status}).`});
} else {
res.render('console.hbs', {errormsg: 'Command sent.'});
}
}
});
app.post('/serverRestart', async (req, res) => {
if (req.session.userId) {
//console.dir("InvokeCommand:", string)
var string = 'restart';
var status = (await postInvokeCommand.postInvokeCommand(string));
if (status == 503) {
//res.redirect('/console');
res.render('console.hbs', {errormsg: 'Error: Server is offline.'});
} else {
//res.redirect('/console');
res.render('console.hbs', {errormsg: 'Sent restart request to server.'});
}
//res.redirect('/console');
} else {
res.render('login.hbs');
}
});
app.post('/serverStop', async (req, res) => {
if (req.session.userId) {
var status = (await postStop.postStop());
if (status != 400) {
//res.redirect('/console');
res.render('console.hbs', {errormsg: 'Error: Server has already stopped.'});
} else {
//res.redirect('/console');
res.render('console.hbs', {errormsg: 'Sent stop request to server.'});
}
//res.redirect('/console');
} else {
res.render('login.hbs');
}
});
app.post('/serverStart', async (req, res) => {
if (req.session.userId) {
var status = (await postStart.postStart());
if (status == 400) {
//res.redirect('/console');
res.render('console.hbs', {errormsg: 'Error: Server has already started.'});
} else {
//res.redirect('/console');
res.render('console.hbs', {errormsg: 'Sent start request to server.'});
}
} else {
res.render('login.hbs');
}
});
/*app.get('/panel/getSettings', (req, res) => {
if (req.session.userId) {
//console.dir("InvokeCommand:", string)
//postStop.postStop('!restart 1');
(async () => {
var string = JSON.parse(await getSettings.getSettings());
var output = jp.query(string, '$')
res.send(output)
})();
} else {
res.render('login.hbs');
}
});*/
/*=============================
AMP LINK
PLAYERS MANAGEMENT
============================*/
app.get('/players', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
res.render('chatplayers.hbs');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.get('/banned', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
res.render('bannedplayers.hbs');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.get('/players/banned', consoleLimiter, async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var players = await getAllBannedPlayers.getAllBannedPlayers();
if (process.env.UGC_SERVICE_TYPE == 'eos') {
if (players == 500) {
res.send(`<h3>Server is offline. Please start it in order to get live player stats.</h3>`);
} else {
var parsed2 = JSONbig.parse(players)
//console.log(parsed)
var values = jp.query(parsed2, '$.*')
let platform = `{"platformType":[`;
for (let i = 0; i < values.length; i++) {
const value = BigInt(values[i]);
if (value < BigInt('10')) {
platform += `"Unknown",`
} else if (value < BigInt('9000000000000000')) {
platform += `"XBOX",`
} else if (value < BigInt('79999999999999999')) {
platform += `"Steam",`;
} else {
platform += `"PlayStation",`;
}
}
platform = platform.slice(0, -1);
platform = platform+"]}";
platform = JSON.parse(platform)
var result = jp.query(platform, '$.*')
//result = jp.query(result, '$.*.*');
}
//const playernames = "Cannot be determined with current configuration."
res.render('banned.hbs', {play: playersList, eosnames: values, names: undefined, platforms: result});
} else if (process.env.UGC_SERVICE_TYPE == "steam") {
var platform = "Steam";
var players = await getAllBannedPlayers.getAllBannedPlayers();
var playernames = await getSteamPlayerSummaries.getSteamPlayerSummaries(process.env.STEAM_API_TOKEN, players);
var playernames2 = JSON.parse(playernames)
var playernames3 = jp.query(playernames2, '$.response.players.*')
if (players == 500) {
res.send(`<h3>Server is offline. Please start it in order to get live player stats.</h3>`);
} else {
var parsed2 = JSONbig.parse(players)
//console.log(parsed)
var playersList = jp.query(parsed2, '$.*')
//console.log(playernames3)
res.render('banned.hbs', {play: playersList, names: playernames3, platforms: platform});
}
}
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.get('/players/list', consoleLimiter, async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var players = await getAllPlayers.getAllPlayers();
if (players == 500) {
res.send(`<h3>Server is offline. Please start it in order to get live player stats.</h3>`);
} else {
var parsed = JSONbig.parse(players)
//console.log(parsed)
var playersList = jp.query(parsed, '$.*')
res.render('players.hbs', {play: playersList});
}
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.post('/panel/players/ban/:id', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var id = req.params.id;
await postBanPlayer.postBanPlayer(id);
notify.notify(1, `Player with steam ID of ${id} has been banned.`)
res.redirect('/players');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.post('/panel/players/:id/unban', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var id = req.params.id;
await postUnbanPlayer.postUnbanPlayer(id);
notify.notify(1, `Player with steam ID of ${id} has been unbanned.`)
res.redirect('/banned');
//res.render('bannedplayers.hbs', {output: `Player with steam ID of ${id} has been unbanned`});
} catch (e) {
notify.notify(3, e)
res.render('bannedplayers.hbs', {output: e});
}
} else {
res.render('login.hbs');
}
});
app.post('/panel/players/kick/:id', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var id = req.params.id;
await postKickPlayer.postKickPlayer(id);
notify.notify(1, `Player with steam ID of ${id} has been kicked.`)
res.redirect('/players');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.post('/panel/players/promote/:id', async (req, res) => {
if (req.session.userId) {
try {
var id = req.params.id;
await postPromotePlayer.postPromotePlayer(id);
notify.notify(1, `Player with steam ID of ${id} has been promoted.`)
res.redirect('/players');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.post('/panel/players/demote/:id', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var id = req.params.id;
await postDemotePlayer.postDemotePlayer(id);
notify.notify(1, `Player with steam ID of ${id} has been demoted.`)
res.redirect('/players');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.post('/panel/players/disconnect/:id', async (req, res) => {
if (req.session.userId) {
try {
//console.log('panel')
var id = req.params.id;
await postDisconnectPlayer.postDisconnectPlayer(id);
notify.notify(1, `Player with steam ID of ${id} has been disconnected.`)
res.redirect('/players');
} catch (e) {
notify.notify(3, e)
}
} else {
res.render('login.hbs');
}
});
app.post('/manualban', async (req, res) => {
if (req.session.userId) {
const { banuser } = req.body;
try {
//console.log('panel')
await postBanPlayer.postBanPlayer(banuser);
notify.notify(1, `Player with steam ID of ${banuser} has been banned.`)
res.render('bannedplayers.hbs', {output: `Player with steam ID of ${banuser} has been banned`});
} catch (e) {
notify.notify(3, e)
res.render('bannedplayers.hbs', {output: e});
}
} else {
res.render('login.hbs');
}
});