canaille-globuzma/canaille/backends/__init__.py

116 lines
3 KiB
Python
Raw Normal View History

2023-04-09 21:00:13 +00:00
import importlib
import os
from contextlib import contextmanager
2023-04-09 21:00:13 +00:00
from flask import g
2023-06-05 16:10:37 +00:00
class BaseBackend:
instance = None
def __init__(self, config):
self.config = config
2023-06-05 16:10:37 +00:00
BaseBackend.instance = self
2023-04-09 21:00:13 +00:00
self.register_models()
@classmethod
def get(cls):
return cls.instance
2023-04-08 18:42:38 +00:00
def init_app(self, app):
@app.before_request
2023-04-08 18:42:38 +00:00
def before_request():
return self.setup()
2023-04-08 18:42:38 +00:00
@app.after_request
2023-04-08 18:42:38 +00:00
def after_request(response):
self.teardown()
2023-04-08 18:42:38 +00:00
return response
@contextmanager
def session(self, *args, **kwargs):
yield self.setup(*args, **kwargs)
self.teardown()
@classmethod
def install(self, config, debug=False):
"""
This methods prepares the database to host canaille data.
"""
raise NotImplementedError()
2023-04-08 18:42:38 +00:00
def setup(self):
"""
This method will be called before each http request,
it should open the connection to the backend.
"""
raise NotImplementedError()
def teardown(self):
"""
This method will be called after each http request,
it should close the connections to the backend.
"""
raise NotImplementedError()
@classmethod
def validate(cls, config):
"""
This method should validate the config part dedicated to the backend.
It should raise :class:`~canaille.configuration.ConfigurationError` when
errors are met.
"""
raise NotImplementedError()
2022-11-01 11:25:21 +00:00
def has_account_lockability(self):
"""
Indicates wether the backend supports locking user accounts.
"""
raise NotImplementedError()
2023-04-09 21:00:13 +00:00
def register_models(self):
from canaille.app import models
module = ".".join(self.__class__.__module__.split(".")[:-1] + ["models"])
try:
backend_models = importlib.import_module(module)
except ModuleNotFoundError:
return
model_names = [
"AuthorizationCode",
"Client",
"Consent",
"Group",
"Token",
"User",
]
for model_name in model_names:
models.register(getattr(backend_models, model_name))
def setup_backend(app, backend):
if not backend:
2023-04-15 11:00:02 +00:00
backend_name = list(app.config.get("BACKENDS", {"memory": {}}).keys())[
0
].lower()
2023-04-09 21:00:13 +00:00
module = importlib.import_module(f"canaille.backends.{backend_name}.backend")
backend_class = getattr(module, "Backend")
backend = backend_class(app.config)
backend.init_app(app)
with app.app_context():
g.backend = backend
app.backend = backend
if app.debug:
2023-04-09 21:00:13 +00:00
backend.install(app.config, True)
def available_backends():
return {
elt.name
for elt in os.scandir(os.path.dirname(__file__))
if elt.is_dir() and os.path.exists(os.path.join(elt, "backend.py"))
}