Organise flask app and add update_users and mc to take count of modifications in config

This commit is contained in:
Ethanell 2019-10-27 13:42:41 +01:00
parent fb5d68025c
commit 5a859d3295
4 changed files with 133 additions and 105 deletions

12
app/__init__.py Normal file
View file

@ -0,0 +1,12 @@
from flask import Flask
from flask_jwt import JWT
from configuration import FlaskConfig, authenticate, identity, update_mc, update_users
app = Flask(__name__) # Setup Flask's app
app.config.from_object(FlaskConfig) # Import Flask configuration
jwt = JWT(app, authenticate, identity) # Setup JWT
server = None # Init server
update_mc()
update_users()
from app import routes

112
app.py → app/routes.py Executable file → Normal file
View file

@ -1,99 +1,14 @@
import json
import logging import logging
import json
import subprocess import subprocess
from os import urandom
from os.path import isfile from os.path import isfile
from pathlib import Path from pathlib import Path
from time import sleep from time import sleep
from flask import Flask, abort, jsonify, request from app import app, server
from flask_jwt import JWT, jwt_required from configuration import conf, mcr, mcq, update_users, update_mc
from mcrcon import MCRcon from flask import abort, jsonify, request
from mcstatus import MinecraftServer from flask_jwt import jwt_required
from werkzeug.security import check_password_hash, generate_password_hash
# Create default configuration file
if not isfile("config.json"):
logging.info("No config file, creating nwe one")
conf = {
"Key": str(urandom(24)),
"Users": {"admin": generate_password_hash("admin")},
"Path": "",
"Jar server": "server.jar",
"Server min ram": "1024M",
"Server max ram": "1024M",
"Server ip": "127.0.0.1",
"Rcon port": 25575,
"Rcon passwd": "admin",
"Query port": 25565,
"Properties": {}
}
with open("config.json", "w") as conf_file:
json.dump(conf, conf_file)
# Load configuration file
with open("config.json", "r") as conf_file:
logging.info("Loading configurations")
conf = json.load(conf_file)
# Check s server jar exist
if not isfile(Path(conf["Path"])/conf["Jar server"]):
logging.warning("No server jar found !")
exit()
# Enable elua by default
if not isfile(Path(conf["Path"])/"eula.txt"):
logging.info("No elua.txt, creating new one")
with open(Path(conf["Path"])/"eula.txt") as elua:
elua.write("eula=true")
# Configuration of flask
class Config(object):
SECRET_KEY = conf["Key"]
JWT_AUTH_USERNAME_KEY = "username"
# User object for JWT
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return "User(id='%s')" % self.id
# Convert user form config to User object
# TODO: Support config change
users = list()
for i, u in enumerate(conf["Users"]):
users.append(User(i+1, u, conf["Users"][u]))
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
def authenticate(username, password):
"""
Authentication for JWT
:param username: User's username (str)
:param password: User's password
:return: User's object if correct username and password
"""
user = username_table.get(username, None)
if user and check_password_hash(user.password, password):
return user
def identity(payload):
"""
Get identity for JWT
:param payload: JWT payload
:return: User's object
"""
user_id = payload["identity"]
return userid_table.get(user_id, None)
def update_properties(): def update_properties():
@ -122,16 +37,6 @@ def update_properties():
properties_file.write(properties) properties_file.write(properties)
# Setup of globals variables
app = Flask(__name__) # Setup Flask's app
app.config.from_object(Config) # Import Flask configuration
# TODO: support config change
mcr = MCRcon(conf["Server ip"], conf["Rcon passwd"], conf["Rcon port"]) # Setup Rcon
mcq = MinecraftServer(conf["Server ip"], conf["Query port"]) # Setup Query
jwt = JWT(app, authenticate, identity) # Setup JWT
server = None # Init server
@app.route("/") @app.route("/")
@jwt_required() @jwt_required()
def root(): def root():
@ -261,9 +166,6 @@ def update_config():
# Save configuration changes # Save configuration changes
with open("config.json", "w") as conf_file: with open("config.json", "w") as conf_file:
json.dump(conf, conf_file) json.dump(conf, conf_file)
update_users()
update_mc()
return jsonify(conf) return jsonify(conf)
# Start of the program
if __name__ == "__main__":
app.run(ssl_context="adhoc")

109
configuration.py Normal file
View file

@ -0,0 +1,109 @@
import json
import logging
from os import urandom
from os.path import isfile
from pathlib import Path
from mcrcon import MCRcon
from mcstatus import MinecraftServer
from werkzeug.security import check_password_hash, generate_password_hash
# Create default configuration file
if not isfile("config.json"):
logging.info("No config file, creating nwe one")
conf = {
"Key": str(urandom(24)),
"Users": {"admin": generate_password_hash("admin")},
"Path": "server",
"Jar server": "server.jar",
"Server min ram": "1024M",
"Server max ram": "1024M",
"Server ip": "127.0.0.1",
"Rcon port": 25575,
"Rcon passwd": "admin",
"Query port": 25565,
"Properties": {}
}
with open("config.json", "w") as conf_file:
json.dump(conf, conf_file)
# Load configuration file
with open("config.json", "r") as conf_file:
logging.info("Loading configurations")
conf = json.load(conf_file)
# Check s server jar exist
if not isfile(Path(conf["Path"])/conf["Jar server"]):
logging.warning("No server jar found !")
exit()
# Enable elua by default
if not isfile(Path(conf["Path"])/"eula.txt"):
logging.info("No elua.txt, creating new one")
with open(Path(conf["Path"])/"eula.txt", "w") as elua:
elua.write("eula=true")
mcr = None # Setup Rcon
mcq = None # Setup Query
def update_mc():
global mcr, mcq
mcr = MCRcon(conf["Server ip"], conf["Rcon passwd"], conf["Rcon port"])
mcq = MinecraftServer(conf["Server ip"], conf["Query port"])
# Configuration of flask
class FlaskConfig(object):
SECRET_KEY = conf["Key"]
JWT_AUTH_USERNAME_KEY = "username"
# User object for JWT
class User(object):
def __init__(self, id, username, password):
self.id = id
self.username = username
self.password = password
def __str__(self):
return "User(id='%s')" % self.id
# Users variables init
users = list()
username_table = dict()
userid_table = dict()
def update_users():
"""
Convert user from config to user object and put in users variables
"""
global users, username_table, userid_table
users = [User(i + 1, u, conf["Users"][u]) for i, u in enumerate(conf["Users"])]
username_table = {u.username: u for u in users}
userid_table = {u.id: u for u in users}
def authenticate(username, password):
"""
Authentication for JWT
:param username: User's username (str)
:param password: User's password
:return: User's object if correct username and password
"""
user = username_table.get(username, None)
if user and check_password_hash(user.password, password):
return user
def identity(payload):
"""
Get identity for JWT
:param payload: JWT payload
:return: User's object
"""
user_id = payload["identity"]
return userid_table.get(user_id, None)

5
main.py Normal file
View file

@ -0,0 +1,5 @@
from app import app
# Start of the program
if __name__ == "__main__":
app.run()