[+] Cloudflare support !

Signed-off-by: Charles Le Maux <charles.le-maux@epitech.eu>
This commit is contained in:
Charles Le Maux 2024-07-01 14:42:28 +01:00
parent 6b9df8e668
commit fa6846a0ce
6 changed files with 78 additions and 68 deletions

View File

@ -8,10 +8,10 @@
<h2>Generic Calls</h2>
<form id="genericForm">
Email: <input type="text" id="accountEmail"><br>
Port: <input type="number" id="accountPort"><br>
Name: <input type="text" id="serverName"><br>
Version: <input type="text" id="serverVersion"><br>
Email: <label for="accountEmail"></label><input type="text" id="accountEmail"><br>
Port: <label for="accountPort"></label><input type="number" id="accountPort"><br>
Name: <label for="serverName"></label><input type="text" id="serverName"><br>
Version: <label for="serverVersion"></label><input type="text" id="serverVersion"><br>
<button type="button" class="actionButton" data-action="AccountCreate">Create Account</button>
<button type="button" class="actionButton" data-action="AccountDelete">Delete Account</button>
<button type="button" class="actionButton" data-action="ServerCreate">Create Server</button>
@ -23,33 +23,31 @@
<h2>Update Property</h2>
<form id="updatePropertyForm">
Property: <input type="text" id="update_property"><br>
Value: <input type="text" id="update_value"><br>
Property: <label for="update_property"></label><input type="text" id="update_property"><br>
Value: <label for="update_value"></label><input type="text" id="update_value"><br>
<button type="button" class="actionButton" data-action="UpdateProperty">Update Property</button>
</form>
<h2>Send Command</h2>
<form id="sendCommandForm">
Command: <input type="text" id="command"><br>
Command: <label for="command"></label><input type="text" id="command"><br>
<button type="button" class="actionButton" data-action="Command">Send command</button>
</form>
<h2>Set Subdomain</h2>
<form id="sendCommandForm">
Command: <input type="text" id="subdomain"><br>
Command: <label for="subdomain"></label><input type="text" id="subdomain"><br>
<button type="button" class="actionButton" data-action="SetSubdomain">Send command</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', () => {
const forms = document.querySelectorAll('form');
const buttons = document.querySelectorAll('.actionButton');
buttons.forEach(button => {
button.addEventListener('click', async event => {
const form = event.target.closest('form');
const action = button.dataset.action;
const token = "gqZN3eCHF3V2er3Py3rlgk8u2t83";
const token = "MpkbDMOO8PQddQgB5VgBQdTMWF53";
const framework = "paper";
const subdomain = document.getElementById('subdomain').value;
const email = document.getElementById('accountEmail').value;
@ -100,7 +98,7 @@ document.addEventListener('DOMContentLoaded', () => {
});
function sendRequest(endpoint, payload) {
return fetch(`http://176.165.62.226:3000/${endpoint}`, {
return fetch(`http://localhost:3000/${endpoint}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'

2
app.py
View File

@ -1,7 +1,7 @@
import http
import inspect
from flask import Blueprint, Flask, Response, jsonify, request
from flask import (Blueprint, Flask, Response, jsonify, request)
from flask_cors import CORS
import firebase_manager

44
cloudflare_manager.py Normal file
View File

@ -0,0 +1,44 @@
from cloudflare import Cloudflare
from cloudflare.types.dns import SRVRecord
from cloudflare.types.dns.record_create_params import SRVRecordData
from typing_extensions import Literal
api_key = ('v1.0-6461a24521b5431608149858-953c8f44c3eca9e9f6c23675e3c0d2'
'0662a5960f87a3c8f8ad1a80a882b480b1d05c9924ec4c342e65783dba4c5742bee5cf665df07b3ac21c448ea5c72f7df'
'a46728dbb37f62845e7')
zone_id = "33ddf3f97d1f4fd9be7b0725b848a0d7"
client = Cloudflare(
api_key="d33db5b942cb5cebd76dabb4f495e14a9033a",
api_email="lemauxcharles@yahoo.com",
)
def add_cloudflare_dns(subdomain: str, port: str) -> SRVRecord:
record: Literal["SRV"] = "SRV"
data: SRVRecordData = {
'weight': 5,
'port': int(port),
'priority': 5,
'target': "servii.fr",
port: int(port),
zone_id: zone_id,
}
return client.dns.records.create(
type=record,
name=f'_minecraft._tcp.{subdomain}',
zone_id=zone_id,
priority=5,
data=data,
)
def delete_cloudflare_dns(dns_record_id: str) -> None:
client.dns.records.delete(
dns_record_id=dns_record_id,
zone_id=zone_id,
)
if __name__ == '__main__':
pass

View File

@ -63,43 +63,6 @@ def update_server_property(file_path, property_name, new_value):
file.writelines(content)
def reload_nginx() -> bool:
try:
subprocess.run(['nginx', '-s', 'reload'], check=True)
return True
except subprocess.CalledProcessError as e:
return False
def append_stream_config(port, subdomain, config_file_path='/etc/nginx/sites-available/servii.fr'):
os.makedirs(os.path.dirname(config_file_path), exist_ok=True)
with open(config_file_path, 'r') as file:
content = file.read()
new_content = f"""stream {{
server {{
listen 25565;
listen [::]:25565;
server_name {subdomain}.servii.fr;
proxy_pass 127.0.0.1:{port};
}}
}}\n"""
final_content = content + new_content
with open(config_file_path, 'w') as file:
file.write(final_content)
def remove_stream_config(port, subdomain, config_file_path='/etc/nginx/sites-available/servii.fr'):
pattern = (r'stream {{\s*server {{\s*listen 25565;\s*listen \[\(::\]\):25565;\s*server_name {}.servii\.fr;\s*proxy_pass 127\.0\.0\.1:{};\s*}}}\n'
.format(re.escape(subdomain), port))
with open(config_file_path, 'r') as file:
content = file.read()
cleaned_content = re.sub(pattern, '', content, flags=re.MULTILINE | re.DOTALL)
with open(config_file_path, 'w') as file:
file.write(cleaned_content)
print(f"Stream configuration removed from {config_file_path}")
def log_error(error_type: str, error_message: str):
logging.basicConfig(filename='logs.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',

View File

@ -1,7 +1,9 @@
from http import HTTPStatus
from cloudflare.types.dns import SRVRecord
from firebase_admin.auth import UserRecord
import cloudflare_manager
import file_manager
import firebase_manager
from server_mc_manager import MinecraftServerManager
@ -27,11 +29,14 @@ def set_subdomain(user: UserRecord, subdomain: str) -> tuple[HTTPStatus, str or
if port is None:
return HTTPStatus.NOT_FOUND, "Port not found on database"
try:
file_manager.append_stream_config(port, subdomain)
file_manager.reload_nginx()
record: SRVRecord = cloudflare_manager.add_cloudflare_dns(subdomain, port)
record_id: str = record.id
if record_id is None:
return HTTPStatus.BAD_REQUEST, "Failed to add record to cloudflare"
firebase_manager.update_firestore(user_id, {'cloudflare_entry': str(record_id)})
except Exception as e:
firebase_manager.update_firestore(user_id, {'subdomain': None})
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Nginx configuration failed. {str(e)}"
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Cloudflare configuration failed. {str(e)}"
return HTTPStatus.OK, "Successfully associated subdomain."
except Exception as e:
return HTTPStatus.FORBIDDEN, str(e)
@ -59,7 +64,8 @@ def account_create(user: UserRecord) -> tuple[HTTPStatus, str or None]:
'name': user.display_name,
'photo_url': user.photo_url,
'subdomain': None,
'port': firebase_manager.fetch_port() + 1
'port': firebase_manager.fetch_port() + 1,
'cloudflare_entry': None,
})
return HTTPStatus.CREATED, "Successfully created account."
except Exception as e:
@ -110,19 +116,18 @@ def server_delete(name: str, user: UserRecord) -> tuple[HTTPStatus, str or None]
def account_delete(user: UserRecord, subdomain: str) -> tuple[HTTPStatus, str or None]:
user_id = user.uid
try:
dns_record_id = firebase_manager.get_user_field(user_id, "cloudflare_entry")
if dns_record_id is None:
return HTTPStatus.IM_A_TEAPOT, "Cloudflare 'dns_record_id' not found in Firestore."
cloudflare_manager.delete_cloudflare_dns(dns_record_id)
except Exception as e:
return HTTPStatus.NOT_MODIFIED, f"Account deletion failed. {str(e)}"
try:
firebase_manager.delete_user(user_id)
except Exception as e:
return HTTPStatus.EXPECTATION_FAILED, f"Database deletion failed | {e}"
try:
file_manager.delete_non_empty_folder("users/" + user_id)
try:
port = firebase_manager.get_server_port(user_id)
if port is None:
return HTTPStatus.NOT_FOUND, "User not found on firestore."
firebase_manager.delete_user(user_id)
except Exception as e:
return HTTPStatus.NOT_FOUND, f"Database deletion failed | {e}"
try:
file_manager.remove_stream_config(port, subdomain)
except Exception as e:
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Nginx deletion failed. {str(e)}"
return HTTPStatus.OK, f"Successfully deleted user {user_id}."
except Exception as e:
file_manager.log_error(type(e).__name__, str(e))
@ -175,8 +180,7 @@ def update_property(user: UserRecord, name: str, prop: str, value: str) -> tuple
except FileNotFoundError:
return HTTPStatus.NOT_FOUND, f"Requested server '{name}' not found."
except Exception as e:
print(f"Unhandled error: {type(e).__name__}, {str(e)}")
return HTTPStatus.INTERNAL_SERVER_ERROR, None
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Unhandled error: {type(e).__name__}, {str(e)}"
def run_command(user: UserRecord, command: str, name: str) -> tuple[HTTPStatus, str or None]:

View File

@ -4,3 +4,4 @@ Flask_Cors==4.0.1
google-api-core==2.19.0
PyJWT==2.8.0
gunicorn==20.1.0
cloudflare==3.0.1