Huge refactor

This commit is contained in:
cubernetes 2023-04-14 07:13:17 +02:00
parent 58ecb0bf5e
commit ecca0cda36
4 changed files with 261 additions and 160 deletions

View File

@ -0,0 +1 @@
[]

View File

@ -0,0 +1 @@
[]

300
webserver/main.py Normal file → Executable file
View File

@ -1,3 +1,5 @@
#!/usr/bin/env python3
import os, datetime, requests, random, json, time, string
from werkzeug.security import generate_password_hash
from werkzeug.utils import secure_filename
@ -15,6 +17,8 @@ from oauthlib.oauth2 import WebApplicationClient
from discord_webhook import DiscordWebhook, DiscordEmbed
from base64 import b64decode
STARTED = 0
app = Flask(__name__)
app.config.update(
@ -25,15 +29,14 @@ app.config.update(
login_manager = LoginManager()
login_manager.init_app(app)
class User(UserMixin):
def __init__(self, id):
self.id = id
self.name = "user" + str(id)
self.password = self.name + "_secret"
self.name = 'user' + str(id)
self.password = self.name + '_secret'
def __repr__(self):
return "%d/%s/%s" % (self.id, self.name, self.password)
return '%d/%s/%s' % (self.id, self.name, self.password)
@login_manager.user_loader
def load_user(userid):
@ -42,125 +45,111 @@ def load_user(userid):
def get_username(self):
return self.username
@app.route('/')
def homepage():
return redirect("/login")
return redirect('/login')
@app.route('/login', methods=['GET',"POST"])
@app.route('/login', methods=['GET', 'POST'])
def login_general():
if request.method == "POST":
if request.method == 'POST':
commit_proper = True
try:
username = request.form['username']
password_login = request.form['password_login']
if username == "" and password_login == "":
if username == '' and password_login == '':
commit_proper = False
except:
commit_proper = False
if commit_proper:
all_user_files = os.listdir('database/users')
all_user_files = os.listdir('./database/users')
matching_user_json = None
for user_now in all_user_files:
with open(f'database/users/{user_now}/user.json','r') as user_file:
with open(f'./database/users/{user_now}/user.json') as user_file:
user_json = json.load(user_file)
if user_json["username"] == username or str(user_json["email"]).lower() == username.lower():
if user_json['username'] == username or str(user_json['email']).lower() == username.lower():
matching_user_json = user_json
if not matching_user_json == None:
if matching_user_json["password"] == password_login:
var_user_to_login = User(matching_user_json["userid"])
if matching_user_json['password'] == password_login:
var_user_to_login = User(matching_user_json['userid'])
login_user(var_user_to_login)
return redirect("/d1")
return redirect('/d1')
else:
return render_template("login/invalid_credentials_noti.html")
return render_template('login/invalid_credentials_noti.html')
else:
return render_template("login/invalid_credentials_noti.html")
return render_template('login/invalid_credentials_noti.html')
else:
return render_template("login/invalid_credentials_noti.html")
return render_template('login/invalid_credentials_noti.html')
else:
return render_template("login/main_login.html")
return render_template('login/main_login.html')
@app.route("/logout", methods=['GET']) #logout
@app.route('/logout', methods=['GET'])
def cpdashy_logout_main():
try:
logout_user()
except:
pass #prolly not even logged in
return redirect("/login")
return redirect('/login')
# Main Dashboard start
def extract_time(json):
try:
return int(int(json['timestamp'].split("m")[0])*60 + int(json['timestamp'].split("m")[1].replace("m","").replace("s","").replace(" ","").replace("&nbp;","")))
return json['timestamp']
except KeyError:
return 0
def cpdash_get_sidebar():
with open('templates/sidebar.html','r') as f:
with open('templates/sidebar.html') as f:
sidebar = f.read()
return(sidebar)
return sidebar
@app.route("/d1", methods=['GET']) #main manager dash
@app.route('/d1', methods=['GET']) #main manager dash
def cpdashy_1_main():
global STARTED
if current_user.is_authenticated:
userid = str(current_user.name).replace("user","").replace("User","").replace("USER","")
with open(f'database/users/{userid}/user.json','r') as f:
userid = str(current_user.name).replace('user', '').replace('User', '').replace('USER', '')
with open(f'./database/users/{userid}/user.json') as f:
user_data = json.load(f)
if not os.path.exists("database/temp/sim_running.txt"):
sim_running = "False"
if not os.path.exists('./database/temp/sim_running.txt'):
sim_running = 'False'
else:
with open("database/temp/sim_running.txt","r") as f:
with open('./database/temp/sim_running.txt') as f:
sim_running = f.read()
if not os.path.exists("database/temp/sim_start.txt"):
sim_start_timestamp = "0"
if not os.path.exists('./database/temp/sim_start.txt'):
sim_start_timestamp = '-1'
STARTED = False
else:
with open("database/temp/sim_start.txt","r") as f:
sim_start_timestamp_stamp = int(f.read().split(".")[0])
min, sec = divmod(time.time() - int(sim_start_timestamp_stamp),60)
sim_start_timestamp = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
with open('./database/temp/sim_start.txt') as f:
sim_start_timestamp = f.read()
STARTED = True
if not os.path.exists("database/temp/attack_start.txt"):
attack_start_timestamp = "0"
if not os.path.exists('./database/temp/attack_start.txt'):
attack_start_timestamp = '-1'
else:
with open("database/temp/attack_start.txt","r") as f:
attack_start_timestamp = int(f.read().split(".")[0])
min, sec = divmod(time.time() - int(attack_start_timestamp),60)
attack_start_timestamp = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
with open('./database/temp/attack_start.txt') as f:
attack_start_timestamp = f.read()
with open("database/logs/blue.json","r") as f:
with open('./database/logs/blue.json') as f:
blue_logs_list_ori = json.load(f)
blue_logs_list = []
for blue_log_now in blue_logs_list_ori:
min, sec = divmod(time.time() - int(blue_log_now["timestamp"]),60)
blue_log_now["timestamp"] = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
blue_log_now["origin"] = "blue"
blue_log_now["timeline_class"] = "container_time_right"
blue_log_now["timeline_side"] = "right"
blue_log_now['timestamp'] = str(int(time.time()))
blue_log_now['origin'] = 'blue'
blue_log_now['timeline_class'] = 'container_time_right'
blue_log_now['timeline_side'] = 'right'
blue_logs_list.append(blue_log_now)
with open("database/logs/red.json","r") as f:
with open('./database/logs/red.json') as f:
red_logs_list_ori = json.load(f)
red_logs_list = []
for red_log_now in red_logs_list_ori:
min, sec = divmod(time.time() - int(red_log_now["timestamp"]),60)
red_log_now["timestamp"] = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
red_log_now["origin"] = "red"
red_log_now["timeline_class"] = "container_time"
red_log_now["timeline_side"] = "left"
red_log_now['timestamp'] = str(int(time.time()))
red_log_now['origin'] = 'red'
red_log_now['timeline_class'] = 'container_time'
red_log_now['timeline_side'] = 'left'
red_logs_list.append(red_log_now)
total_logs_list = []
@ -172,66 +161,61 @@ def cpdashy_1_main():
red_logs_list.reverse()
# total_logs_list.reverse()
return render_template("main/dashboard_main1.html",total_logs_list=total_logs_list,attack_start_timestamp=attack_start_timestamp,blue_logs_list=blue_logs_list,red_logs_list=red_logs_list,sim_running=sim_running,sim_start_timestamp=sim_start_timestamp,sidebar_html_insert=cpdash_get_sidebar().replace("active_state_class1","is-active"), profile_picture=user_data["picture"],profile_username=user_data["username"],profile_userid=user_data["userid"],profile_email=user_data["email"])
return render_template('main/dashboard_main1.html', total_logs_list=total_logs_list, attack_start_timestamp=attack_start_timestamp, blue_logs_list=blue_logs_list, red_logs_list=red_logs_list, sim_running=sim_running, sim_start_timestamp=sim_start_timestamp, sidebar_html_insert=cpdash_get_sidebar().replace('active_state_class1', 'is-active'), profile_picture=user_data['picture'], profile_username=user_data['username'], profile_userid=user_data['userid'], profile_email=user_data['email'])
else:
return redirect('/login')
@app.route("/d2", methods=['GET']) #logs
@app.route('/d2', methods=['GET']) #logs
def cpdashy_2_main():
if current_user.is_authenticated:
userid = str(current_user.name).replace("user","").replace("User","").replace("USER","")
with open(f'database/users/{userid}/user.json','r') as f:
userid = str(current_user.name).replace('user', '').replace('User', '').replace('USER', '')
with open(f'./database/users/{userid}/user.json') as f:
user_data = json.load(f)
if not os.path.exists("database/temp/sim_running.txt"):
sim_running = "False"
if not os.path.exists('./database/temp/sim_running.txt'):
sim_running = 'False'
else:
with open("database/temp/sim_running.txt","r") as f:
with open('./database/temp/sim_running.txt') as f:
sim_running = f.read()
if not os.path.exists("database/temp/sim_start.txt"):
sim_start_timestamp = "0"
if not os.path.exists('./database/temp/sim_start.txt'):
sim_start_timestamp = '0'
else:
with open("database/temp/sim_start.txt","r") as f:
sim_start_timestamp_stamp = int(f.read().split(".")[0])
with open('./database/temp/sim_start.txt') as f:
sim_start_timestamp = int(f.read().split('.')[0])
min, sec = divmod(time.time() - int(sim_start_timestamp_stamp),60)
sim_start_timestamp = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
min, sec = divmod(int(time.time()) - int(sim_start_timestamp), 60)
sim_start_timestamp = str(int(min)) + 'm ' + str(int(round(sec, 0))) + 's'
if not os.path.exists("database/temp/attack_start.txt"):
attack_start_timestamp = "0"
if not os.path.exists('./database/temp/attack_start.txt'):
attack_start_timestamp = '0'
else:
with open("database/temp/attack_start.txt","r") as f:
attack_start_timestamp = int(f.read().split(".")[0])
with open('./database/temp/attack_start.txt') as f:
attack_start_timestamp = int(f.read().split('.')[0])
min, sec = divmod(time.time() - int(attack_start_timestamp),60)
attack_start_timestamp = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
min, sec = divmod(int(time.time()) - int(attack_start_timestamp), 60)
attack_start_timestamp = str(int(min)) + 'm ' + str(int(round(sec, 0))) + 's'
with open("database/logs/blue.json","r") as f:
with open('./database/logs/blue.json') as f:
blue_logs_list_ori = json.load(f)
blue_logs_list = []
for blue_log_now in blue_logs_list_ori:
min, sec = divmod(time.time() - int(blue_log_now["timestamp"]),60)
blue_log_now["timestamp"] = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
blue_log_now["origin"] = "blue"
blue_log_now["timeline_class"] = "container_time_right"
blue_log_now["timeline_side"] = "right"
min, sec = divmod(int(time.time()) - int(blue_log_now['timestamp']), 60)
blue_log_now['timestamp'] = str(int(min)) + 'm ' + str(int(round(sec, 0))) + 's'
blue_log_now['origin'] = 'blue'
blue_log_now['timeline_class'] = 'container_time_right'
blue_log_now['timeline_side'] = 'right'
blue_logs_list.append(blue_log_now)
with open("database/logs/red.json","r") as f:
with open('./database/logs/red.json') as f:
red_logs_list_ori = json.load(f)
red_logs_list = []
for red_log_now in red_logs_list_ori:
min, sec = divmod(time.time() - int(red_log_now["timestamp"]),60)
red_log_now["timestamp"] = str(int(min)) + "m " + str(int(round(sec,0))) + "s"
red_log_now["origin"] = "red"
red_log_now["timeline_class"] = "container_time"
red_log_now["timeline_side"] = "left"
min, sec = divmod(int(time.time()) - int(red_log_now['timestamp']), 60)
red_log_now['timestamp'] = str(int(min)) + 'm ' + str(int(round(sec, 0))) + 's'
red_log_now['origin'] = 'red'
red_log_now['timeline_class'] = 'container_time'
red_log_now['timeline_side'] = 'left'
red_logs_list.append(red_log_now)
total_logs_list = []
@ -243,97 +227,113 @@ def cpdashy_2_main():
red_logs_list.reverse()
total_logs_list.reverse()
return render_template("main/dashboard_main2.html",total_logs_list=total_logs_list,attack_start_timestamp=attack_start_timestamp,blue_logs_list=blue_logs_list,red_logs_list=red_logs_list,sim_running=sim_running,sim_start_timestamp=sim_start_timestamp,sidebar_html_insert=cpdash_get_sidebar().replace("active_state_class2","is-active"), profile_picture=user_data["picture"],profile_username=user_data["username"],profile_userid=user_data["userid"],profile_email=user_data["email"])
return render_template('main/dashboard_main2.html', total_logs_list=total_logs_list, attack_start_timestamp=attack_start_timestamp, blue_logs_list=blue_logs_list, red_logs_list=red_logs_list, sim_running=sim_running, sim_start_timestamp=sim_start_timestamp, sidebar_html_insert=cpdash_get_sidebar().replace('active_state_class2', 'is-active'), profile_picture=user_data['picture'], profile_username=user_data['username'], profile_userid=user_data['userid'], profile_email=user_data['email'])
else:
return redirect('/login')
@app.route("/d1/startsim", methods=['GET']) #start and stop the sim
@app.route('/d1/startsim', methods=['GET']) #start and stop the sim
def cpdashy_startsim():
if current_user.is_authenticated:
if os.path.exists("database/temp/sim_running.txt"):
with open("database/temp/sim_running.txt","r") as f:
if os.path.exists('./database/temp/sim_running.txt'):
with open('./database/temp/sim_running.txt') as f:
current_state = f.read()
if not current_state == "False":
with open("database/temp/sim_running.txt","w") as f:
f.write("False")
if not current_state == 'False':
with open('./database/temp/sim_running.txt', 'w') as f:
f.write('False')
else:
clear_session_full()
with open("database/temp/sim_start.txt","w") as f:
f.write(str(time.time()))
with open("database/temp/sim_running.txt","w") as f:
f.write("True")
with open('./database/temp/sim_start.txt', 'w') as f:
f.write(str(int(time.time())))
with open('./database/temp/sim_running.txt', 'w') as f:
f.write('True')
else:
clear_session_full()
with open("database/temp/sim_start.txt","w") as f:
f.write(str(time.time()))
with open("database/temp/sim_running.txt","w") as f:
f.write("True")
return redirect("/d1")
with open('./database/temp/sim_start.txt', 'w') as f:
f.write(str(int(time.time())))
with open('./database/temp/sim_running.txt', 'w') as f:
f.write('True')
return redirect('/d1')
else:
return redirect('/login')
# API
def clear_session_full():
for file_now in ["database/temp/sim_start.txt","database/temp/attack_start.txt","database/temp/sim_running.txt","database/temp/attack_running.txt"]:
for file_now in ['./database/temp/sim_start.txt', './database/temp/attack_start.txt', './database/temp/sim_running.txt', './database/temp/attack_running.txt']:
try:
os.remove(file_now)
except:
pass
with open("database/logs/red.json","w") as f:
f.write("[]")
with open("database/logs/blue.json","w") as f:
f.write("[]")
with open('./database/logs/red.json', 'w') as f:
f.write('[]')
with open('./database/logs/blue.json', 'w') as f:
f.write('[]')
@app.route("/api/red", methods=['POST'])
@app.route('/api/logs', methods=['GET'])
def api_get_logs():
with open('./database/logs/red.json') as f:
red_raw = f.read()
red = json.loads(red_raw)
with open('./database/logs/blue.json') as f:
blue_raw = f.read()
blue = json.loads(blue_raw)
result = {
'red': red,
'blue': blue
}
return json.dumps(result, ensure_ascii=False)
@app.route('/api/red', methods=['POST'])
def api_red_logs():
global STARTED
temp_json_n = request.json
print("red log received")
print('red log received')
print(temp_json_n)
if temp_json_n["data"].lower() == "start of attack":
with open("database/temp/attack_start.txt",'w') as f:
f.write(str(temp_json_n["timestamp"]))
if STARTED:
if temp_json_n['data'].lower() == 'start of attack':
with open('./database/temp/attack_start.txt', 'w') as f:
f.write(str(temp_json_n['timestamp']))
with open("database/logs/red.json","r") as f:
logs_list = json.load(f)
logs_list.append(temp_json_n)
with open("database/logs/red.json","w") as f:
json.dump(logs_list,f)
with open('./database/logs/red.json') as f:
logs_list = json.load(f)
logs_list.append(temp_json_n)
with open('./database/logs/red.json', 'w') as f:
json.dump(logs_list, f, ensure_ascii=False)
return("log saved")
return 'log saved'
else:
return 'simulation not started'
@app.route("/api/blue", methods=['POST'])
@app.route('/api/blue', methods=['POST'])
def api_blue_logs():
global STARTED
temp_json_n = request.json
temp_json_n["data"] = b64decode(temp_json_n["data"]).decode("utf-8").replace("\n","<br>")
print("blue log received")
print('blue log received')
print(temp_json_n)
if STARTED:
with open('./database/logs/blue.json') as f:
logs_list = json.load(f)
logs_list.append(temp_json_n)
with open('./database/logs/blue.json', 'w') as f:
json.dump(logs_list, f, ensure_ascii=False)
with open("database/logs/blue.json","r") as f:
logs_list = json.load(f)
logs_list.append(temp_json_n)
with open("database/logs/blue.json","w") as f:
json.dump(logs_list,f)
return("log saved")
return 'log saved'
else:
return 'simulation not started'
# Error handling
@app.errorhandler(401)
def custom_401(error):
return redirect("/")
return redirect('/')
@app.errorhandler(404)
def custom_404(error):
return redirect("/")
return redirect('/')
clear_session_full()
if __name__ == '__main__':
app.run(host='185.78.255.231', threaded=True,use_reloader=True, port=443, ssl_context=('/etc/letsencrypt/live/network.kyudev.xyz/fullchain.pem', '/etc/letsencrypt/live/network.kyudev.xyz/privkey.pem'))
app.run(host='0.0.0.0', threaded=True, use_reloader=True, port=8088)

View File

@ -77,7 +77,7 @@
overflow: hidden;
width: 100%;
border-radius: 20px;
font-size: 15px;
font-size: 12px;
font-weight: 500;
box-shadow: 0 20px 50px rgba(0, 0, 0, 0.3);
position: relative;
@ -1305,7 +1305,7 @@
<a href="#" style="text-decoration: none;color: #ff66d9;">
<div class="video-by" title="Time elapsed since the Attack started">Time since Attack start</div>
{% autoescape false %}
<div class="video-name padding_stat_n">{{ attack_start_timestamp }}</div>
<div class="video-name padding_stat_n" id="attackstart" data-start="{{ attack_start_timestamp }}">0</div>
{% endautoescape %}
</a>
</div>
@ -1313,12 +1313,12 @@
<a href="#" style="text-decoration: none;color: #ff66d9;">
<div class="video-by" title="Time since the sim started">Time since Sim start</div>
{% autoescape false %}
<div class="video-name padding_stat_n">{{ sim_start_timestamp }}</div>
<div class="video-name padding_stat_n" id="simstart" data-start="{{ sim_start_timestamp }}">0</div>
{% endautoescape %}
</a>
</div>
<div class="video anim" style="--delay: .5s">
<a href="/d1/startsim" style="text-decoration: none;color: #ff66d9;">
<a id="start_toggle" href="/d1/startsim" style="text-decoration: none;color: #ff66d9;">
<div class="video-by" title="Start or Stop the Simulation" id="start_stop_sim_btn">Start Simulation</div>
<div class="video-name padding_stat_n">click here</div>
</a>
@ -1499,21 +1499,93 @@
}
</style>
<div>
<div class="timeline">
{% for blue_log_now in total_logs_list %}
<div class='{{ blue_log_now["timeline_class"] }} {{ blue_log_now["timeline_side"] }}' style="box-sizing: border-box;">
<div id="timeline" class="timeline">
<!--
{% for log_entry in total_logs_list %}
<div class='{{ log_entry["timeline_class"] }} {{ log_entry["timeline_side"] }}' style="box-sizing: border-box;">
<div class="content_time" style="box-sizing: border-box;">
{% autoescape false %}
<h2>{{ blue_log_now["timestamp"] }}</h2>
<p>{{ blue_log_now["data"] }}</p>
<h2>{{ log_entry["timestamp"] }}</h2>
<p>{{ log_entry["data"] }}</p>
{% endautoescape %}
</div>
</div>
{% endfor %}
-->
</div>
</div>
</div>
<script>
function to_min_s(txt_timestamp_start, txt_timestamp_end) {
let delta = parseInt(txt_timestamp_end) - parseInt(txt_timestamp_start);
let quotient = Math.floor(delta / 60);
let remainder = delta % 60;
return `${quotient}m ${remainder}s`;
}
function timestamp_sort(x, y) {
if (parseInt(x.timestamp) < parseInt(y.timestamp)) {
return -1;
}
if (parseInt(x.timestamp) > parseInt(y.timestamp)) {
return 1;
}
return 0;
}
function flatten_dict(data) {
let res = [];
data.red.forEach(data_entry => {
res.push({
team: 'red',
data: data_entry.data,
timestamp: data_entry.timestamp
});
});
data.blue.forEach(data_entry => {
res.push({
team: 'blue',
data: data_entry.data,
timestamp: data_entry.timestamp
});
});
return res;
}
function populateTimeline(data) {
data = flatten_dict(data);
let tl = document.getElementById('timeline');
tl.innerHTML = '';
data.forEach(data_entry => {
entry_div = document.createElement('div');
container = document.createElement('div');
timestamp_h2 = document.createElement('h2');
data_tag = document.createElement('p');
timestamp_txt = document.createTextNode(to_min_s(document.getElementById('simstart').getAttribute('data-start'), data_entry.timestamp));
data_txt = document.createTextNode(data_entry.data);
data_tag.appendChild(data_txt);
timestamp_h2.appendChild(timestamp_txt);
container.appendChild(timestamp_h2);
container.appendChild(data_tag);
container.classList.add("content_time");
container.setAttribute("style", 'box-sizing: border-box;');
entry_div.appendChild(container);
if (data_entry.team === 'red') {
entry_div.classList.add("container_time");
} else {
entry_div.classList.add("container_time_right");
}
if (data_entry.team === 'red') {
entry_div.classList.add("left");
} else {
entry_div.classList.add("right");
}
entry_div.setAttribute("style", 'box-sizing: border-box;');
tl.appendChild(entry_div);
});
}
</script>
<script>
if("{{ sim_running }}" == "True"){
console.log("1")
@ -1522,7 +1594,34 @@
console.log("2")
document.getElementById("start_stop_sim_btn").innerHTML = "Start Simulation"
}
const iid = setInterval(() => {
let start = parseInt(document.getElementById("simstart").getAttribute("data-start"));
let end = ~~(Date.now()/1e3);
if (start === -1 && document.getElementById('start_stop_sim_btn').innerHTML === 'Start Simulation' && document.getElementById("attackstart").getAttribute("data-start") === "-1") {
document.getElementById("simstart").innerHTML = "0";
} else {
document.getElementById("simstart").innerHTML = end - start;
if (document.getElementById('start_stop_sim_btn').innerHTML === 'Start Simulation')
{
document.getElementById("simstart").setAttribute("data-start", "-1");
document.getElementById("simstart").innerHTML = "0";
}
}
start = parseInt(document.getElementById("attackstart").getAttribute("data-start"));
end = ~~(Date.now()/1e3);
if (start === -1) {
document.getElementById("attackstart").innerHTML = "0";
} else {
document.getElementById("attackstart").innerHTML = end - start;
}
fetch('/api/logs')
.then(resp => resp.json())
.then(populateTimeline);
}, 1000);
</script>
</div>
</div>
</body>
</body>