Merge branch 'pluginify' of groeger-clan.duckdns.org:newgeruecht into pluginify

This commit is contained in:
Tim Gröger 2021-01-23 09:32:20 +01:00
commit a0d1567b3c
5 changed files with 84 additions and 26 deletions

View File

@ -71,7 +71,7 @@ def install_all():
roleController.create_permissions(plugin.permissions) roleController.create_permissions(plugin.permissions)
def create_app(): def create_app(test_config=None):
app = Flask(__name__) app = Flask(__name__)
app.json_encoder = CustomJSONEncoder app.json_encoder = CustomJSONEncoder
CORS(app) CORS(app)
@ -79,7 +79,7 @@ def create_app():
with app.app_context(): with app.app_context():
from flaschengeist.database import db from flaschengeist.database import db
configure_app(app) configure_app(app, test_config)
db.init_app(app) db.init_app(app)
__load_plugins(app) __load_plugins(app)

View File

@ -8,33 +8,44 @@ from werkzeug.middleware.proxy_fix import ProxyFix
from flaschengeist import _module_path, logger from flaschengeist import _module_path, logger
def __update(d, u): # Default config:
config = {}
def update_dict(d, u):
for k, v in u.items(): for k, v in u.items():
if isinstance(v, collections.abc.Mapping): if isinstance(v, collections.abc.Mapping):
d[k] = __update(d.get(k, {}), v) d[k] = update_dict(d.get(k, {}), v)
else: else:
d[k] = v d[k] = v
return d return d
# Default config: def read_configuration():
config = {} global config
__paths = [_module_path, Path.home() / ".config"] paths = [_module_path, Path.home() / ".config"]
if "FLASCHENGEIST_CONF" in os.environ: if "FLASCHENGEIST_CONF" in os.environ:
__paths.append(Path(os.environ.get("FLASCHENGEIST_CONF"))) paths.append(Path(os.environ.get("FLASCHENGEIST_CONF")))
for loc in __paths:
try: for loc in paths:
with (loc / "flaschengeist.toml").open() as source: try:
logger.info("Reading config file from >{}<".format(loc)) with (loc / "flaschengeist.toml").open() as source:
__update(config, toml.load(source)) print("Reading config file from >{}<".format(loc))
except IOError: update_dict(config, toml.load(source))
pass except IOError:
# Always enable this builtin plugins! pass
__update(config, {"auth": {"enabled": True}, "roles": {"enabled": True}, "users": {"enabled": True}})
def configure_app(app): def configure_app(app, test_config=None):
global config
if test_config is None:
read_configuration()
else:
update_dict(config, test_config)
# Always enable this builtin plugins!
update_dict(config, {"auth": {"enabled": True}, "roles": {"enabled": True}, "users": {"enabled": True}})
logger_config = toml.load(_module_path / "logging.toml") logger_config = toml.load(_module_path / "logging.toml")
if "LOGGING" in config: if "LOGGING" in config:
if "level" in config["LOGGING"]: if "level" in config["LOGGING"]:
@ -52,12 +63,15 @@ def configure_app(app):
else: else:
app.config["SECRET_KEY"] = config["FLASCHENGEIST"]["secret_key"] app.config["SECRET_KEY"] = config["FLASCHENGEIST"]["secret_key"]
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://{user}:{passwd}@{host}/{database}".format( if test_config is None:
user=config["DATABASE"]["user"], app.config["SQLALCHEMY_DATABASE_URI"] = "mysql://{user}:{passwd}@{host}/{database}".format(
passwd=config["DATABASE"]["password"], user=config["DATABASE"]["user"],
host=config["DATABASE"]["host"], passwd=config["DATABASE"]["password"],
database=config["DATABASE"]["database"], host=config["DATABASE"]["host"],
) database=config["DATABASE"]["database"],
)
else:
app.config["SQLALCHEMY_DATABASE_URI"] = f"sqlite+pysqlite://{config['DATABASE']['file_path']}"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
if "root" in config["FLASCHENGEIST"]: if "root" in config["FLASCHENGEIST"]:

View File

@ -21,7 +21,7 @@ setup(
# Needed for python < 3.7 # Needed for python < 3.7
"backports-datetime-fromisoformat", "backports-datetime-fromisoformat",
], ],
extras_require={"ldap": ["flask_ldapconn", "ldap3"]}, extras_require={"ldap": ["flask_ldapconn", "ldap3"], "tests": ["pytest"]},
entry_points={ entry_points={
"flaschengeist.plugin": [ "flaschengeist.plugin": [
# Authentication providers # Authentication providers

28
tests/conftest.py Normal file
View File

@ -0,0 +1,28 @@
import os
import tempfile
import pytest
from flaschengeist.app import create_app, install_all
@pytest.fixture
def app():
db_fd, db_path = tempfile.mkstemp()
app = create_app(
{
"TESTING": True,
"DATABASE": {"file_path": f"/{db_path}"},
"FLASCHENGEIST": {"auth": "auth_plain"},
"auth_plain": {"enabled": True},
}
)
with app.app_context():
install_all()
yield app
os.close(db_fd)
os.unlink(db_path)
@pytest.fixture
def client(app):
return app.test_client()

16
tests/test_auth.py Normal file
View File

@ -0,0 +1,16 @@
import pytest
# with app.app_context():
# engine = database.db.engine
# with engine.connect() as connection:
# connection.execute("")
def test_login_decorator(client):
"""Testing the login_required decorator"""
# No header at all
assert client.get("/auth").status_code == 401
# Invalid header
assert client.get("/auth", headers={"Authorization": "INVALID"}).status_code == 401
# Invalid Token
assert client.get("/auth", headers={"Authorization": "Bearer INVALID"}).status_code == 401