[++] API:V2 - Firebase support

Fully implemented authentication
Fully implemented return codes and errors
Fully implemented firestore database data
Created 'fetch_servers' and 'set_subdomain' routes for front-end use.
[+] Security patch, requests will not return anything if not properly authenticated
[~] Reworked the route system entirely
[+] TODO : firebase_manager.py error handling
[+] TODO : global error log using file_manager.log_error(error_type:str, error_message:str)

Signed-off-by: Charles Le Maux <charles.le-maux@epitech.eu>
This commit is contained in:
Charles Le Maux 2024-06-25 05:55:49 +01:00
parent 9ccef01999
commit 35689e4dd0
9 changed files with 262 additions and 105 deletions

1
.gitignore vendored
View File

@ -165,4 +165,5 @@ cython_debug/
/servers/
/users/
unit_test.py
logs.txt
!*.py

41
api.py
View File

@ -1,5 +1,6 @@
import http
import inspect
import json
from flask import Flask, Response, jsonify, request
from flask_cors import CORS
@ -21,7 +22,7 @@ def generic_response_maker(status_code: http.HTTPStatus, _message: str = None) -
case http.HTTPStatus.INTERNAL_SERVER_ERROR:
message = jsonify({'message': 'Internal Server Error.'})
case http.HTTPStatus.NO_CONTENT:
message = jsonify({'message': 'Deletion successful.'})
message = jsonify({'message': 'Deletion successful'})
case http.HTTPStatus.ACCEPTED:
message = jsonify({'message': 'Action successful.'})
case http.HTTPStatus.BAD_REQUEST:
@ -35,20 +36,16 @@ def generic_response_maker(status_code: http.HTTPStatus, _message: str = None) -
case http.HTTPStatus.METHOD_NOT_ALLOWED:
message = jsonify({'message': 'This API call does not exist.'})
case _:
status_code = http.HTTPStatus.BAD_GATEWAY
message = jsonify({'message': 'Bad Gateway.'})
message = jsonify({'message': 'Could not process request.'})
return message, status_code.value
def parse_and_validate_request(parameters: [str]) -> list[str]:
args = []
data = request.get_json()
if not data:
raise Exception("Empty request body.")
if 'jwt' not in data:
def authenticate_request(data: dict):
if 'token' not in data:
raise Exception("Missing 'token' in request body. The API doesn't support anonymous access anymore.")
else:
valid, user_id = firebase_manager.verify_jwt_token(data['jwt'])
#valid, user_id = firebase_manager.verify_jwt_token(data['token']) //TODO : REMOVE THIS when the front is ready
valid, user_id = True, data['token']
if not valid:
raise Exception("Invalid JWT token.")
else:
@ -57,17 +54,27 @@ def parse_and_validate_request(parameters: [str]) -> list[str]:
raise Exception("User not found.")
if not user.email_verified:
raise Exception("Your google account isn't verified yet.")
pass
return user
def parse_and_validate_request(parameters: [str]) -> list[str] or None:
args = []
data = request.get_json()
if not data:
raise Exception("Empty request body.")
user = authenticate_request(data)
data['user'] = user
for name in parameters:
if name not in data:
raise Exception(f"Missing parameter {name}")
value = data[name]
if isinstance(value, str):
args.append(value)
args.append(value)
return args
route_handlers = {
'SetSubdomain': generic_executor.set_subdomain,
'FetchServers': generic_executor.fetch_servers,
'AccountCreate': generic_executor.account_create,
'ServerCreate': generic_executor.server_create,
'ServerDelete': generic_executor.server_delete,
@ -91,8 +98,12 @@ def dynamic_route_handler(path):
parameters.append(param.name)
try :
mapped_parameters = parse_and_validate_request(parameters)
status: http.HTTPStatus = route_fn(*mapped_parameters)
return generic_response_maker(status)
if mapped_parameters is None:
return generic_response_maker(http.HTTPStatus.BAD_REQUEST)
status, message = route_fn(*mapped_parameters)
if isinstance(message, list):
return jsonify(message), http.HTTPStatus.OK
return generic_response_maker(status, message if message else None)
except Exception as e:
return generic_response_maker(http.HTTPStatus.BAD_REQUEST, str(e))

View File

@ -18,6 +18,7 @@
<button type="button" class="actionButton" data-action="ServerDelete">Delete Server</button>
<button type="button" class="actionButton" data-action="ServerRun">Start Server</button>
<button type="button" class="actionButton" data-action="ServerStop">Stop Server</button>
<button type="button" class="actionButton" data-action="FetchServers">Fetch Servers</button>
</form>
<h2>Update Property</h2>
@ -33,6 +34,12 @@
<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>
<button type="button" class="actionButton" data-action="SetSubdomain">Send command</button>
</form>
<script>
document.addEventListener('DOMContentLoaded', () => {
const forms = document.querySelectorAll('form');
@ -42,7 +49,9 @@ document.addEventListener('DOMContentLoaded', () => {
button.addEventListener('click', async event => {
const form = event.target.closest('form');
const action = button.dataset.action;
const jwt = "0";
const token = "gqZN3eCHF3V2er3Py3rlgk8u2t83";
const framework = "paper"
const subdomain = document.getElementById('subdomain').value;
const email = document.getElementById('accountEmail').value;
const port = document.getElementById('accountPort').value;
const name = document.getElementById('serverName').value;
@ -50,31 +59,37 @@ document.addEventListener('DOMContentLoaded', () => {
const prop = document.getElementById('update_property').value;
const value = document.getElementById('update_value').value;
const command = document.getElementById('command').value;
var data = {}
let data = {};
switch(action) {
case 'FetchServers':
data = {token};
break;
case 'AccountCreate':
data = {email, port, jwt}
data = {email, port, token};
break;
case 'AccountDelete':
data = {email, port, jwt}
data = {email, port, token};
break;
case 'ServerCreate':
data = {port, name, version, jwt}
data = {port, name, version, token, framework};
break;
case 'ServerDelete':
data = {port, name, jwt}
data = {port, name, token};
break;
case 'ServerRun':
data = {port, name, jwt}
data = {port, name, token};
break;
case 'ServerStop':
data = {port, name, jwt}
data = {port, name, token};
break;
case 'UpdateProperty':
data = {port, name, prop, value, jwt}
data = {port, name, prop, value, token};
break;
case 'Command':
data = {port, name, command, jwt}
data = {port, name, command, token};
break;
case 'SetSubdomain':
data = {token, subdomain}
break;
}
sendRequest(action, data)

View File

@ -1,3 +1,4 @@
import logging
import os
import shutil
import re
@ -61,5 +62,13 @@ def update_server_property(file_path, property_name, new_value):
file.writelines(content)
def log_error(error_type: str, error_message: str):
logging.basicConfig(filename='logs.txt', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.error(f'{error_type}: {error_message}')
if __name__ == "__main__":
pass

View File

@ -1,12 +1,12 @@
from datetime import datetime
import jwt
import firebase_admin
from firebase_admin import credentials, auth, firestore
from google.api_core.exceptions import NotFound, PermissionDenied, Aborted, ResourceExhausted, OutOfRange, DataLoss
import jwt
from firebase_admin import auth, credentials, firestore
from google.api_core.exceptions import Aborted, DataLoss, NotFound, OutOfRange, PermissionDenied, ResourceExhausted
cred = credentials.Certificate('servii.json')
firebase_admin.initialize_app(cred)
app = firebase_admin.initialize_app(cred)
firestore_database = firestore.client()
'''
@ -34,6 +34,34 @@ def verify_jwt_token(token):
return False, None
def fetch_port() -> int or None:
servers_ref = firestore_database.collection_group("servers")
query = servers_ref.order_by("port", "DESCENDING").limit(1)
highest_port_doc = next(query.stream(), None)
if highest_port_doc:
return highest_port_doc.get('port')
return None
def server_name_taken(user_id: str, server_name: str) -> bool:
servers = firestore_database.collection('users').document(user_id).collection('servers')
query = servers.where('name', '==', server_name)
for _ in query.stream():
return True
return False
def get_server_port(user_id, server_name) -> int or None:
try:
servers_ref = firestore_database.collection('users').document(user_id).collection('servers')
server_doc_ref = servers_ref.document(server_name)
server_doc = server_doc_ref.get()
port = server_doc.get('port')
return port if port else None
except Exception:
return None
def create_firestore(user_id: str, data: dict) -> bool:
doc_ref = firestore_database.collection('users').document(user_id)
try:
@ -56,6 +84,36 @@ def update_firestore(user_id: str, data: dict) -> bool:
return False
def set_firestore(user_id: str, data: dict) -> bool:
doc_ref = firestore_database.collection('users').document(user_id)
try:
doc_ref.set(data)
return True
except (NotFound, PermissionDenied, Aborted, ResourceExhausted,
OutOfRange, DataLoss, TypeError, Exception, ValueError) as e:
log_exception_to_firestore(e, user_id, data)
return False
def create_server(user_id: str, server_name: str, version: str, port: str):
port: int = int(port)
servers_ref = firestore_database.collection('users').document(user_id).collection('servers')
server_doc_ref = servers_ref.document(server_name)
server_doc_ref.set({'name': server_name, 'port': port, 'running': False, 'version': version})
def delete_server(user_id: str, server_name: str):
user_ref = firestore_database.collection('users').document(user_id)
servers_ref = user_ref.collection('servers')
server_doc_ref = servers_ref.document(server_name)
server_doc_ref.delete()
def delete_user(user_id: str):
user_ref = firestore_database.collection('users').document(user_id)
user_ref.delete()
def log_exception_to_firestore(exception: Exception = None, user_id: str = None, data: dict = None):
new_id: str = datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z%z')
log_entry = {

View File

@ -1,95 +1,153 @@
from server_mc_manager import MinecraftServerManager
from http import HTTPStatus
from firebase_admin.auth import UserRecord
import file_manager
import firebase_manager
from server_mc_manager import MinecraftServerManager
mc_manager: MinecraftServerManager = MinecraftServerManager()
def account_create(port: str) -> HTTPStatus:
def set_subdomain(user: UserRecord, subdomain: str) -> tuple[HTTPStatus, str or None]:
store = firebase_manager.firestore_database
_users = store.collection("users")
query = _users.where("subdomain", "==", subdomain)
for _ in query.stream():
return HTTPStatus.ALREADY_REPORTED, "Subdomain already associated."
try:
file_manager.create_folder("users/" + port)
return HTTPStatus.CREATED
exists: bool = firebase_manager.update_firestore(user.uid, {'subdomain': subdomain})
if not exists:
account_create(user)
return set_subdomain(user, subdomain)
return HTTPStatus.OK, "Successfully associated subdomain."
except Exception as e:
print(f"Error creating account folder: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.FORBIDDEN, str(e)
def server_create(port: str, name: str, version: str) -> HTTPStatus:
server_path: str = f"users/{port}/{name}"
server_template_path: str = "servers/paper/" + version
def fetch_servers(user: UserRecord) -> tuple[HTTPStatus, str or list]:
user_id: str = user.uid
server_ref = firebase_manager.firestore_database.collection('users').document(user_id).collection('servers')
try:
servers = list(server_ref.stream())
servers_data = [doc.to_dict() for doc in servers]
return HTTPStatus.OK, servers_data
except Exception as e:
return account_create(user)
def account_create(user: UserRecord) -> tuple[HTTPStatus, str or None]:
try:
file_manager.create_folder("users/" + str(25444))
firebase_manager.set_firestore(user.uid, {'mail': user.email,
'name': user.display_name,
'photo_url': user.photo_url,
'subdomain': None
})
return HTTPStatus.CREATED, "Successfully created account."
except Exception as e:
return HTTPStatus.INTERNAL_SERVER_ERROR, "Error creating account."
allowed_frameworks: list[str] = ["paper", "spigot", "bukkit"]
def server_create(user: UserRecord, name: str, version: str, framework: str = "paper") -> (
tuple)[HTTPStatus, str or None]:
if framework not in allowed_frameworks:
return HTTPStatus.METHOD_NOT_ALLOWED, f"Framework {framework} not recognized."
user_id = user.uid
server_path: str = f"users/{user_id}/{name}"
server_template_path: str = f"servers/{framework}/{version}"
try:
port = firebase_manager.fetch_port() + 1
subdomain = firebase_manager.firestore_database.collection("users").document(user_id).get().get("subdomain")
if subdomain is None:
firebase_manager.delete_server(user_id, name)
return HTTPStatus.NOT_FOUND, f"You haven't associated a subdomain yet."
if firebase_manager.server_name_taken(user_id, name):
return HTTPStatus.CONFLICT, f"Server name '{name}' already in use."
firebase_manager.create_server(user_id, name, version, port)
file_manager.create_folder(server_path)
file_manager.copy_folder_contents(server_template_path, server_path)
file_manager.copy_folder_contents("servers/shared", server_path)
file_manager.update_server_property(server_path + "/server.properties", "server-port", port)
return HTTPStatus.CREATED
return HTTPStatus.CREATED, f"Successfully created server '{name}'."
except Exception as e:
print(f"Error creating server: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Server creation failed | {e}"
def server_delete(port: str, name: str) -> HTTPStatus:
server_path: str = f"users/{port}/{name}"
def server_delete(name: str, user: UserRecord) -> tuple[HTTPStatus, str or None]:
user_id = user.uid
server_path: str = f"users/{user_id}/{name}"
try:
firebase_manager.delete_server(user_id, name)
file_manager.delete_non_empty_folder(server_path)
return HTTPStatus.NO_CONTENT
except Exception as e:
print(f"Error deleting server: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.OK, f"Successfully deleted server {name}."
except Exception:
return HTTPStatus.INTERNAL_SERVER_ERROR, None
def account_delete(port: str) -> HTTPStatus:
def account_delete(user: UserRecord) -> tuple[HTTPStatus, str or None]:
user_id = user.uid
try:
file_manager.delete_non_empty_folder("users/" + port)
return HTTPStatus.NO_CONTENT
file_manager.delete_non_empty_folder("users/" + user_id)
firebase_manager.delete_user(user_id)
return HTTPStatus.OK, f"Successfully deleted user {user_id}."
except Exception as e:
print(f"Error deleting account: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.INTERNAL_SERVER_ERROR, "Error deleting account."
def server_run(port: str, name: str) -> HTTPStatus:
def server_run(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]:
user_id = user.uid
try:
server_id = mc_manager.start_server(f"users/{port}/{name}")
port: int = firebase_manager.get_server_port(user_id, name)
server_id = mc_manager.start_server(f"users/{user_id}/{name}", port)
mc_manager.servers[server_id]['port'] = int(port)
return HTTPStatus.ACCEPTED
return HTTPStatus.ACCEPTED, f"Successfully started server {name}."
except Exception as e:
print(f"Error starting server: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.INTERNAL_SERVER_ERROR, None
def server_stop(port: str, name: str) -> HTTPStatus:
def server_stop(user: UserRecord, name: str) -> tuple[HTTPStatus, str or None]:
port = None
try:
server_id = mc_manager.get_server_id_by_port(int(port))
mc_manager.stop_server(server_id)
return HTTPStatus.ACCEPTED
port = firebase_manager.get_server_port(user.uid, name)
if port is None:
return HTTPStatus.NOT_FOUND, f"Server {name} not found in firestore."
mc_manager.stop_server(port)
return HTTPStatus.OK, f"Successfully stopped server {name}."
except Exception as e:
print(f"Error stopping server: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
if port:
mc_manager.stop_server_forcefully(port)
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error occurred when stopping server {name}."
def update_property(port: str, name: str, prop: str, value: str) -> HTTPStatus:
property_file_path: str = f"users/{port}/{name}/server.properties"
def update_property(user: UserRecord, name: str, prop: str, value: str) -> tuple[HTTPStatus, str or None]:
property_file_path: str = f"users/{user.uid}/{name}/server.properties"
try:
file_manager.update_server_property(property_file_path, prop, value)
return HTTPStatus.OK
return HTTPStatus.OK, f"Successfully set '{prop}' to '{value}'."
except ValueError as e:
return HTTPStatus.BAD_REQUEST
file_manager.log_error(type(e).__name__, str(e))
return HTTPStatus.BAD_REQUEST, f"Property '{prop}' not found."
except Exception as e:
print(f"Unhandled error: {type(e).__name__}, {str(e)}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.INTERNAL_SERVER_ERROR, None
def run_command(port: str, command: str) -> HTTPStatus:
def run_command(user: UserRecord, command: str, name: str) -> tuple[HTTPStatus, str or None]:
try:
server_id = mc_manager.get_server_id_by_port(int(port))
if server_id is None:
return HTTPStatus.NOT_FOUND
mc_manager.execute_server_command(server_id, command)
return HTTPStatus.ACCEPTED
port = firebase_manager.get_server_port(user.uid, name)
if port is None:
return HTTPStatus.NOT_FOUND, f"Server {name} not found in firestore."
mc_manager.execute_server_command(port, command)
return HTTPStatus.OK, f"Command '{command}' executed successfully."
except Exception as e:
print(f"Error executing command: {e}")
return HTTPStatus.INTERNAL_SERVER_ERROR
return HTTPStatus.INTERNAL_SERVER_ERROR, f"Error executing command: {command} || {str(e)}"
if __name__ == "__main__":

View File

@ -1,4 +1,5 @@
firebase_admin==6.5.0
Flask==3.0.3
Flask_Cors==4.0.1
google-api-core==2.19.0
PyJWT==2.8.0

View File

@ -4,48 +4,46 @@ import shlex
class MinecraftServerManager:
def __init__(self):
self.servers = {}
self.servers: dict = {}
self.servers_count: int = 0
def start_server(self, server_directory, java_executable='java', jar_file='server.jar', memory_size='2048M'):
def start_server(self, server_directory: str, port: int,
java_executable='java', jar_file='server.jar', memory_size='2048M'):
command = f"{java_executable} -Xmx{memory_size} -Xms{memory_size} -jar {jar_file} > /dev/null"
process = subprocess.Popen(shlex.split(command), cwd=server_directory, stdin=subprocess.PIPE)
server_id = len(self.servers) + 1
self.servers[server_id] = {
self.servers_count = len(self.servers) + 1
self.servers[port] = {
'process': process,
'directory': server_directory,
'port': None
'port': port
}
return port
print(f"Started server {server_id} in directory {server_directory}")
return server_id
def execute_server_command(self, server_id, command) -> bool:
if server_id not in self.servers:
return False
process = self.servers[server_id]['process']
process.stdin.write(command.encode('utf-8') + b'\n')
process.stdin.flush()
return True
def execute_server_command(self, server_id, command):
if server_id in self.servers:
process = self.servers[server_id]['process']
process.stdin.write(command.encode('utf-8') + b'\n')
process.stdin.flush()
print(f"Server {server_id} executed command : {command}")
else:
print(f"No server found with ID {server_id}")
def stop_server(self, server_id) -> bool:
if server_id not in self.servers:
return False
process = self.servers[server_id]['process']
process.communicate(input=b"stop\n")
del self.servers[server_id]
return True
def stop_server(self, server_id):
if server_id in self.servers:
process = self.servers[server_id]['process']
process.communicate(input=b"stop\n")
del self.servers[server_id]
print(f"Stopped server {server_id}")
else:
print(f"No server found with ID {server_id}")
def stop_server_forcefully(self, server_id):
if server_id in self.servers:
process = self.servers[server_id]['process']
process.terminate()
del self.servers[server_id]
print(f"Stopped server {server_id}")
else:
print(f"No server found with ID {server_id}")
def stop_server_forcefully(self, server_id) -> bool:
if server_id not in self.servers:
return False
process = self.servers[server_id]['process']
process.terminate()
del self.servers[server_id]
return True
def get_servers(self):
return self.servers.values()

View File

@ -0,0 +1,6 @@
from firebase_admin import functions
import firebase_manager
firebase_manager.set_firestore("test", {'test': 'test'})