Expose hook to inject database connection logic on the fly (#4505)

* Expose hook to inject database connection logic on the fly

This environment configuration setting hook allows administrators to
alter the database connection parameters on the fly based on user
information. This can be use for a variety of purposes:

* rewire a subset of users to use different database user accounts
* pass user related information to the database for logging or QoS
purposes
* ...

* Fixes
This commit is contained in:
Maxime Beauchemin
2018-03-06 22:35:46 -08:00
committed by GitHub
parent d817b8ddbb
commit b63dc91cd1
2 changed files with 19 additions and 0 deletions

View File

@@ -377,6 +377,22 @@ HIVE_POLL_INTERVAL = 5
# an XSS security vulnerability
ENABLE_JAVASCRIPT_CONTROLS = False
# A callable that allows altering the database conneciton URL and params
# on the fly, at runtime. This allows for things like impersonation or
# arbitrary logic. For instance you can wire different users to
# use different connection parameters, or pass their email address as the
# username. The function receives the connection uri object, connection
# params, and user object, and returns the mutated uri and params objects.
# Example:
# def DB_CONNECTION_MUTATOR(uri, params, user):
# if user and user.email:
# uri.username = user.email
# return uri, params
#
# Note that the returned uri and params are passed directly to sqlalchemy's
# as such `create_engine(url, **params)`
DB_CONNECTION_MUTATOR = None
try:
if CONFIG_PATH_ENV_VAR in os.environ:
# Explicitly import config module that is not in pythonpath; useful

View File

@@ -675,6 +675,9 @@ class Database(Model, AuditMixinNullable, ImportMixin):
if configuration:
params['connect_args'] = {'configuration': configuration}
DB_CONNECTION_MUTATOR = config.get('DB_CONNECTION_MUTATOR')
if DB_CONNECTION_MUTATOR:
url, params = DB_CONNECTION_MUTATOR(url, params, g.user)
return create_engine(url, **params)
def get_reserved_words(self):