-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
887 lines (770 loc) · 27.8 KB
/
Copy pathmain.py
File metadata and controls
887 lines (770 loc) · 27.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
from flask import (
Flask,
jsonify,
render_template,
request,
redirect,
session,
url_for,
Response,
)
import handler
import requests
import sqlite3
import base64
import server
# Don't need to put into requirements file because it's required by flask
# already.
from jinja2 import Environment, FileSystemLoader
from urllib.parse import urlparse
from waitress import serve
import configurationlib
import time
import configuration_manager
import secrets
import printedcolors
import network_setup
import distro_handler
import random
colors = printedcolors.Color
def debug_print(message, color=""):
if color == "":
reset = ""
else:
reset = colors.reset
if DEBUG:
print(color + message + reset)
print(colors.fg.cyan + "Temporary SSH Session Manager" + colors.reset)
print("")
exit_error = False
print(colors.fg.lightblue + "Testing Docker Connection..." + colors.reset, end=" ")
if not handler.test_docker_connection():
print(colors.fg.red + "FAIL" + colors.reset)
exit_error = True
else:
print(colors.fg.green + "OK" + colors.reset)
print(
colors.fg.lightblue + "Validating distro configuration..." + colors.reset, end=" "
)
try:
distro_handler.validate_distros()
print(colors.fg.green + "OK" + colors.reset)
except Exception as e:
print(colors.fg.red + "FAIL" + colors.reset)
exit_error = True
print(colors.fg.red + str(e) + colors.reset)
if exit_error:
print(
colors.fg.red
+ "One or more errors were encountered. Please fix the errors and try again."
+ colors.reset
)
exit(1)
network_setup.setup_network()
config = configurationlib.Instance("config.json", format=configurationlib.Format.JSON)
detect_already_configured = configurationlib.Instance(
"DELETE_THIS_FILE_TO_RESET_CONFIGURATION.py", format=configurationlib.Format.PYTHON
)
try:
CONFIGURED = detect_already_configured.get()["CONFIGURED"]
except BaseException:
print(
colors.fg.red + "Configuration file not found. Creating one..." + colors.reset
)
print(colors.fg.green + "Using default configuration." + colors.reset)
configuration_manager.init()
CONFIGURED = False
print(
colors.fg.green
+ "Configuration file created. Please restart the application."
+ colors.reset
)
exit(0)
# Define Jinja2 Env
env = Environment(loader=FileSystemLoader("templates"))
try:
DEBUG = config.get()["DEBUG_MODE"]
except BaseException:
print(
colors.fg.red
+ "Error: Configuration missing. Things may go very wrong."
+ colors.reset
)
if DEBUG:
print(colors.fg.yellow + "Debug mode enabled." + colors.reset)
debug_print("Loading configuration...", colors.fg.green)
try:
REQUIRE_AUTH = config.get()["REQUIRE_AUTH"]
except BaseException:
debug_print(
"Error: Configuration missing. Things may go very wrong.", colors.fg.red
)
REQUIRE_AUTH = True # To avoid errors
debug_print("Configuration loaded.", colors.fg.green)
if config.get()["INSTALL_AGENT_INTO_CONTAINERS_FOR_MANAGEMENT"]:
debug_print("Initializing websocker server...", colors.fg.green)
server.start()
debug_print("Websocket server initialized.", colors.fg.green)
def is_authorized(email):
if config.get()["ALLOW_ALL_VALID_KOKOAUTH_ACCOUNTS_TO_CREATE_SESSIONS"]:
return True
ALLOWED_EMAILS = config.get()["ALLOWED_KOKOAUTH_ACCOUNTS_EMAIL"]
if is_admin(email):
return True
return email in ALLOWED_EMAILS
def is_admin(email):
ADMIN_EMAILS = config.get()["ADMIN_KOKOAUTH_ACCOUNT_EMAIL_ADDRESS"]
return email in ADMIN_EMAILS
def authenticated(session):
if REQUIRE_AUTH:
conn = sqlite3.connect("containers.db")
c = conn.cursor()
try:
c.execute(
"SELECT session FROM session WHERE session=?", (session["session"],)
)
except BaseException:
debug_print("Session not found in database.", colors.fg.red)
conn.close()
return False
session = c.fetchone()
conn.close()
return session is not None
return True
def sync_database_with_docker_containers_state():
debug_print("Syncing database with Docker containers state...", colors.fg.green)
conn = sqlite3.connect("containers.db")
cursor = conn.cursor()
# Iterate over all containers and check if they are: (running, stopped,
# exists).
containers = cursor.execute("SELECT * FROM containers")
# Check if container exist.
for container in containers:
# Check if container exists
exist = handler.check_container_existence(container[1])
if exist:
handler.check_container_existence(container[1])
else:
# Container does not exist
debug_print(
f"Container {container[1]} does not exist. Deleting...", colors.fg.red
)
cursor.execute("DELETE FROM containers WHERE name=?", (container[1],))
conn.commit()
continue
# Refresh containers
containers = cursor.execute("SELECT * FROM containers")
# Check container's state (running, stopped).
for container in containers:
state = handler.fetch_container_state(container[1])
bool_state = True if state == "running" else False
if container[6] != bool_state:
debug_print(
f"Container {container[1]} state changed from {container[6]} to {bool_state}.",
colors.fg.green,
)
if state is True:
cursor.execute(
"UPDATE containers SET active = ? WHERE name = ?",
(True, container[1]),
)
conn.commit()
else:
cursor.execute(
"UPDATE containers SET active = ? WHERE name = ?",
(False, container[1]),
)
conn.commit()
sync_database_with_docker_containers_state()
def create_database():
debug_print("Creating database if not exists...", colors.fg.green)
conn = sqlite3.connect("containers.db")
c = conn.cursor()
# c.execute("ALTER TABLE containers ADD COLUMN active INTEGER;") # TODO:
# add pre-script and post-script to run before and after running this
c.execute("""CREATE TABLE IF NOT EXISTS containers
(id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT,
username TEXT,
password TEXT,
user TEXT,
port INTEGER,
active INTEGER,
dev_port INTEGER)""")
c.execute("""CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT)""")
c.execute("""CREATE TABLE IF NOT EXISTS session
(id INTEGER PRIMARY KEY AUTOINCREMENT,
user TEXT,
session TEXT)
""")
c.execute("""CREATE TABLE IF NOT EXISTS api_key (
id INTEGER PRIMARY KEY AUTOINCREMENT,
api_key TEXT,
user TEXT)""")
conn.commit()
conn.close()
app = Flask(__name__)
app.secret_key = config.get()["APP_SECRET"]
@app.route("/")
def home():
if authenticated(session):
return render_template(
"home.html",
username=session["username"],
authorized=is_authorized(session["username"]),
admin=is_admin(session["username"]),
distros=distro_handler.get_distro_list(),
)
else:
return redirect(url_for("auth"))
@app.route("/apikey/generate", methods=["POST"])
def generate_api_key():
if authenticated(session):
conn = sqlite3.connect("containers.db")
c = conn.cursor()
# Make sure the user has not already generated an API key
# c.execute('SELECT * FROM api_key WHERE user=?', (session['username'],))
# if c.fetchone() is not None:
# # Get the user's API Key
# api = c.execute('SELECT api_key FROM api_key WHERE user=?', (session['username'],)).fetchone()[0]
# return f"<p>{api}</p>"
# else:
# Generate a new API key
new_api_key = "stm_" + str(secrets.token_hex(32))
c.execute(
"INSERT INTO api_key (api_key, user) VALUES (?, ?)",
(new_api_key, session["username"]),
)
conn.commit()
conn.close()
return "<p>" + str(new_api_key) + "</p>"
else:
return "<p>You are not authorized to access this page.</p>"
@app.route("/apikey/delete", methods=["POST"])
def delete_api_key():
if authenticated(session):
api_key = request.json.get("api_key")
if api_key:
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute("DELETE FROM api_key WHERE api_key=?", (api_key,))
conn.commit()
conn.close()
return "API key deleted successfully."
else:
return "API key not provided."
@app.route("/apikey/get")
def get_api_key():
if authenticated(session):
conn = sqlite3.connect("containers.db")
c = conn.cursor()
# Get all of the user's API Keys
c.execute("SELECT api_key FROM api_key WHERE user=?", (session["username"],))
api_keys = [row[0] for row in c.fetchall()]
conn.close()
return jsonify(api_keys)
else:
return "You are not authorized to access this page."
@app.route("/apikey/dashboard")
def api_key_dashboard():
if authenticated(session):
return render_template("api_key.html", username=session["username"])
else:
return redirect(url_for("auth"))
def validate_api_key(key):
# Check if the API key is valid
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute("SELECT * FROM api_key WHERE api_key=?", (key,))
result = c.fetchone()
conn.close()
if result is None:
return False
else:
return True
@app.route("/api/get_user_containers", methods=["GET"])
def get_user_containers_api():
# Get the API key from the request headers
api_key = request.headers.get("Authorization")
# Validate the API key
if not validate_api_key(api_key):
return jsonify({"error": "Invalid API key"}), 401
# Assuming request.url_root is defined
url = request.url_root
parsed_url = urlparse(url)
# Constructing the base URL without scheme and port
base_url_no_scheme = parsed_url.hostname + parsed_url.path.rstrip("/")
# Get the username from the API key
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute("SELECT user FROM api_key WHERE api_key=?", (api_key,))
result = c.fetchone()
if result is None:
return jsonify({"error": "Invalid API key"}), 401
username = result[0]
# Get the user's containers
c.execute("SELECT * FROM containers WHERE user=?", (username,))
containers = c.fetchall()
conn.close()
container_list = []
for container in containers:
container_details = {
"name": container[1],
"username": container[2],
"password": container[3],
"port": container[5],
"exposed_port": container[6],
"hostname": base_url_no_scheme,
"active": container[7],
}
container_list.append(container_details)
return jsonify(container_list)
@app.route("/install/<distro>")
def install_distro(distro):
if distro_handler.validate_distro(distro):
url = request.url_root
template = env.get_template(distro_handler.get_install_file(distro))
rendered_script = template.render(url=url)
return Response(rendered_script, mimetype="text/plain")
else:
return jsonify({"error": "Invalid distro"}), 400
def get_random_port(
starting_port=int(config.get()["STARTING_PORT_FOR_CONTAINERS"]),
ending_port=int(config.get()["ENDING_PORT_FOR_CONTAINERS"]),
):
# Connect to the SQLite database
conn = sqlite3.connect("containers.db")
cursor = conn.cursor()
# Fetch all existing ports from the 'containers' table
cursor.execute("SELECT port FROM containers")
existing_ports = {row[0] for row in cursor.fetchall()}
# Close the database connection
conn.close()
while True:
# Generate a random port number
random_port = random.randint(starting_port, ending_port)
# Check if the generated port is already in use
if random_port not in existing_ports:
return random_port
def get_random_outsider_port(
starting_port=int(config.get()["STARTING_PORT_FOR_CONTAINERS"]) + 1,
ending_port=int(config.get()["ENDING_PORT_FOR_CONTAINERS"]) + 319,
):
# Connect to the SQLite database
conn = sqlite3.connect("containers.db")
cursor = conn.cursor()
# Fetch all existing ports from the 'containers' table
cursor.execute("SELECT dev_port FROM containers")
existing_ports = {row[0] for row in cursor.fetchall()}
# Close the database connection
conn.close()
while True:
# Generate a random port number
random_port = random.randint(starting_port, ending_port)
# Check if the generated port is already in use
if random_port not in existing_ports:
return random_port
@app.route("/create_container", methods=["POST"])
def create_container_route():
time.sleep(5)
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
if not is_authorized(session["username"]):
return jsonify({"error": "You are not authorized to create containers."}), 403
conn = sqlite3.connect("containers.db")
c = conn.cursor()
# Assuming request.url_root is defined
url = request.url_root
parsed_url = urlparse(url)
data = request.get_json() # Use this if sending JSON
distro = data.get("distro") # Access the 'distro' key
c.execute("SELECT user FROM containers WHERE user=?", (session["username"],))
# Fetch all results
rows = c.fetchall()
# Count the number of rows
row_count = len(rows)
if config.get()["MAX_CONTAINERS_PER_USER"] == 0:
pass # No limit
elif row_count >= config.get()["MAX_CONTAINERS_PER_USER"]:
return jsonify(
{
"error": "You have reached the maximum number of containers per user.",
"code": 1002,
}
), 403
# Constructing the base URL without scheme and port
base_url_no_scheme = parsed_url.hostname + parsed_url.path.rstrip("/")
name, username, password, port, exposed_port = handler.create_container(
url + f"""/install/{distro}""",
port=get_random_port(),
outsider_port=get_random_outsider_port(),
distro=distro,
) # TODO: Add non-static token.
if name is not None:
c.execute(
"INSERT INTO containers (name, username, password, user, port, dev_port, active) VALUES (?, ?, ?, ?, ?, ?, ?)",
(name, username, password, session["username"], port, exposed_port, True),
)
conn.commit()
conn.close()
return jsonify(
{
"name": name,
"username": username,
"hostname": base_url_no_scheme,
"port": f"{port}",
"exposed_port": exposed_port,
"password": password,
"ssh_command": f"ssh {username}@{base_url_no_scheme} -p {port}",
}
)
@app.route("/container/restart", methods=["POST"])
def restart_container():
user = session.get("username")
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
if not is_authorized(session["username"]):
return jsonify({"error": "You are not authorized to restart containers."}), 403
# Checking if the user has access to the container using the username
conn = sqlite3.connect("containers.db")
c = conn.cursor()
perms_check = c.execute(
"SELECT user FROM containers WHERE name=? AND user=?",
(request.args.get("id"), user),
).fetchone()
if perms_check is None:
return jsonify(
{
"error": "You are not authorized to restart this container or this container never existed."
}
), 403
container_name = request.args.get("id")
if container_name:
c.execute(
"UPDATE containers SET active = ? WHERE name = ?",
(False, request.args.get("id")),
).fetchone()
handler.restart_container(container_name)
c.execute(
"UPDATE containers SET active = ? WHERE name = ?",
(True, request.args.get("id")),
).fetchone()
conn.commit()
conn.close()
return jsonify({"message": "Container restarted."})
else:
conn.close()
return jsonify({"error": "No container ID provided."}), 400
@app.route("/container/stop", methods=["POST"])
def stop_container():
user = session.get("username")
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
if not is_authorized(session["username"]):
return jsonify({"error": "You are not authorized to stop containers."}), 403
# Checking if the user has access to the container using the username
conn = sqlite3.connect("containers.db")
c = conn.cursor()
perms_check = c.execute(
"SELECT user FROM containers WHERE name=? AND user=?",
(request.args.get("id"), user),
).fetchone()
if perms_check is None:
return jsonify(
{
"error": "You are not authorized to stop this container or this container never existed."
}
), 403
container_name = request.args.get("id")
if container_name:
c.execute(
"UPDATE containers SET active = ? WHERE name = ?",
(False, request.args.get("id")),
).fetchone()
handler.stop_container(container_name)
conn.commit()
conn.close()
return jsonify({"message": "Container stopped."})
@app.route("/container/start", methods=["POST"])
def start_container():
user = session.get("username")
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
if not is_authorized(session["username"]):
return jsonify({"error": "You are not authorized to start containers."}), 403
# Checking if the user has access to the container using the username
conn = sqlite3.connect("containers.db")
c = conn.cursor()
perms_check = c.execute(
"SELECT user FROM containers WHERE name=? AND user=?",
(request.args.get("id"), user),
).fetchone()
if perms_check is None:
return jsonify(
{
"error": "You are not authorized to start this container or this container never existed."
}
), 403
container_name = request.args.get("id")
if container_name:
c.execute(
"UPDATE containers SET active = ? WHERE name = ?",
(True, request.args.get("id")),
).fetchone()
handler.start_container(container_name)
conn.commit()
conn.close()
return jsonify({"message": "Container started."})
@app.route("/auth")
def auth():
base_url = url_for("auth_callback", _external=True)
encoded_data = base64.b64encode(base_url.encode()).decode()
return redirect(
"https://kokoauth.kokodev.cc/auth?name=TemporarySSHSessionManager&callback="
+ encoded_data
)
@app.route("/auth/callback")
def auth_callback():
code = request.args.get("session")
if code:
response = requests.get(
f"https://kokoauth.kokodev.cc/api/v1/get-user-info?session={code}"
)
if response.status_code == 200:
user_info = response.json()
username = user_info.get("email")
if username:
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute("SELECT username FROM users WHERE username=?", (username,))
if c.fetchone() is None:
c.execute("INSERT INTO users (username) VALUES (?)", (username,))
c.execute(
"INSERT INTO session (user, session) VALUES (?, ?)",
(username, code),
)
conn.commit()
conn.close()
session["username"] = username
session["session"] = code
return redirect(url_for("home"))
else:
debug_print(
"Error: Username does not persist from kokoauth.", colors.fg.red
)
else:
debug_print("Error: Authentication failed.", colors.fg.red)
else:
debug_print("Error: Authentication failed.", colors.fg.red)
return redirect(url_for("auth"))
@app.route("/agent/handshake")
def agent_handshake():
# TODO: Add port and scheme changing from config
return jsonify(
{
"message": "OK",
"code": 200,
"port": config.get()["AGENT_PORT"],
"scheme": "ws",
}
)
@app.route("/agent/download")
def download_agent():
# Assuming request.url_root is defined
url = request.url_root
parsed_url = urlparse(url)
# Constructing the base URL without scheme and port
base_url_no_scheme = parsed_url.hostname + parsed_url.path.rstrip("/")
script = (
'''import asyncio
import websockets
import requests
import subprocess
import os
import time
import json
import psutil
host = "'''
+ base_url_no_scheme
+ '''"
schemed_host = "'''
+ url
+ """"
async def report_status(websocket):
# Gather system status
cpu_usage = psutil.cpu_percent()
ram_usage = psutil.virtual_memory().percent
net_io = psutil.net_io_counters()
bytes_sent = net_io.bytes_sent
bytes_recv = net_io.bytes_recv
# Create a status message in JSON format
status_message = {
"cpu_usage": cpu_usage,
"ram_usage": ram_usage,
"bytes_sent": bytes_sent,
"bytes_recv": bytes_recv,
}
# Send the status to the server as a JSON string
await websocket.send(json.dumps(status_message))
async def listen_for_commands():
uri = scheme + "://" + host + ":" + str(port)
while True:
try:
async with websockets.connect(uri) as websocket:
while True:
command = await websocket.recv()
if command == '{"message": "request_report_status"}':
await report_status(websocket)
else:
print(f"{command}")
except:
print("Agent disconnected. Reconnecting in 20 seconds...")
time.sleep(20)
if __name__ == "__main__":
response = requests.get(schemed_host + "agent/handshake").json()
if response['message'] == "OK" and response['code'] == 200:
# Awesome! Ready to connect.
port = int(response['port'])
scheme = response['scheme']
else:
print("Error: Agent handshake failed.")
exit(1)
asyncio.run(listen_for_commands())"""
)
return Response(script, mimetype="text/plain")
@app.route("/get_user_containers", methods=["GET"])
def get_user_containers():
user = session.get("username")
if not authenticated(session):
return "UNAUTHENTICATED", 401
url = request.url_root
parsed_url = urlparse(url)
# Constructing the base URL without scheme and port
base_url_no_scheme = parsed_url.hostname + parsed_url.path.rstrip("/")
try:
conn = sqlite3.connect("containers.db")
c = conn.cursor()
if config.get()["ALLOW_ADMIN_TO_ACCESS_USER_CONTAINERS"] and is_admin(user):
c.execute(
"SELECT name, username, password, port, dev_port, active FROM containers"
)
else:
c.execute(
"SELECT name, username, password, port, dev_port, active FROM containers WHERE user=?",
(user,),
)
containers = c.fetchall()
conn.close()
except sqlite3.Error as e:
debug_print(f"Error while fetching user containers: {e}", colors.fg.red)
return jsonify([]), 500
if containers:
return jsonify(
[
{
"name": container[0],
"username": container[1],
"password": container[2],
"port": container[3],
"exposed_port": container[4],
"hostname": base_url_no_scheme,
"active": container[5],
}
for container in containers
]
)
else:
return jsonify([]), 500
@app.route("/get_connection_details", methods=["GET"])
def get_connection_details():
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
url = request.url_root
parsed_url = urlparse(url)
# Constructing the base URL without scheme and port
base_url_no_scheme = parsed_url.hostname + parsed_url.path.rstrip("/")
id = request.args.get("id")
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute(
"SELECT name, username, password, port, dev_port, active FROM containers WHERE name=? AND user=?",
(id, session["username"]),
)
container = c.fetchone()
conn.close()
if container:
return jsonify(
{
"name": container[0],
"username": container[1],
"exposed_port": container[4],
"hostname": base_url_no_scheme,
"password": container[2],
"ssh_command": f"ssh {container[1]}@{base_url_no_scheme} -p {container[3]}",
"port": container[3],
"active": container[5],
}
)
else:
return jsonify({"error": "Container not found."}), 404
@app.route("/delete_container", methods=["DELETE"])
def delete_containers():
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
debug_print(
f"Deleting container with id: {request.args.get('id')}", colors.fg.green
)
id = request.args.get("id")
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute(
"DELETE FROM containers WHERE name=? AND user=?", (id, session["username"])
)
handler.delete_container(id)
conn.commit()
conn.close()
time.sleep(2)
return jsonify({"success": True})
@app.route("/admin")
def admin():
if not authenticated(session):
return redirect(url_for("auth"))
if not is_admin(session["username"]):
return redirect(url_for("home"))
return render_template("admin.html", username=session["username"])
@app.route("/admin/danger/session/clear", methods=["DELETE"])
def clear_sessions():
if not authenticated(session):
return jsonify({"error": "You are not logged in."}), 401
if not is_admin(session["username"]):
return jsonify({"error": "You are not authorized to clear sessions."}), 403
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute("DELETE FROM session")
conn.commit()
conn.close()
return jsonify({"success": True})
@app.route("/logout")
def logout():
conn = sqlite3.connect("containers.db")
c = conn.cursor()
c.execute("DELETE FROM session WHERE session=?", (session["session"],))
conn.commit()
conn.close()
session.pop("username", None)
session.pop("session", None)
return redirect(url_for("home"))
create_database()
if DEBUG:
debug_print(
"WARNING: DEBUG mode is enabled. Non-Production WSGI server will be used.",
colors.fg.yellow,
)
app.run(host="0.0.0.0", port=config.get()["WEB_DASHBORD_PORT"], debug=DEBUG)
else:
print(
"Dashboard server started on 0.0.0.0:" + str(config.get()["WEB_DASHBORD_PORT"])
)
serve(app, host="0.0.0.0", port=config.get()["WEB_DASHBORD_PORT"])