diff options
author | Frederick Muriuki Muriithi | 2023-08-04 12:49:40 +0300 |
---|---|---|
committer | Frederick Muriuki Muriithi | 2023-08-04 12:49:40 +0300 |
commit | bd99071174bfa80d179dd32673200f51000b86b5 (patch) | |
tree | ab15db002983ddebf10ea6e632b2d0b05b3455d9 /gn_auth/__init__.py | |
parent | 8b7c598407a5fea9a3d78473e72df87606998cd4 (diff) | |
download | gn-auth-bd99071174bfa80d179dd32673200f51000b86b5.tar.gz |
Initialise the application and update some module imports
Diffstat (limited to 'gn_auth/__init__.py')
-rw-r--r-- | gn_auth/__init__.py | 65 |
1 files changed, 65 insertions, 0 deletions
diff --git a/gn_auth/__init__.py b/gn_auth/__init__.py index e69de29..4ef2892 100644 --- a/gn_auth/__init__.py +++ b/gn_auth/__init__.py @@ -0,0 +1,65 @@ +import os +import sys +import logging + +from flask import Flask + +from . import settings + +class ConfigurationError(Exception): + """Raised in case of a configuration error.""" + +def __check_secret_key__(app: Flask) -> None: + """Verify secret key is not empty.""" + if app.config.get("SECRET_KEY", "") == "": + raise ConfigurationError("The `SECRET_KEY` settings cannot be empty.") + +def check_mandatory_settings(app: Flask) -> None: + """Verify that mandatory settings are defined in the application""" + undefined = tuple( + setting for setting in ( + "SECRET_KEY", "SQL_URI", "AUTH_DB", "AUTH_MIGRATIONS", + "OAUTH2_SCOPE") + if setting not in app.config) + if len(undefined) > 0: + raise ConfigurationError( + "You must provide values for the following settings: " + + "\t* " + "\n\t* ".join(undefined)) + + __check_secret_key__(app) + +def override_settings_with_envvars( + app: Flask, ignore: tuple[str, ...]=tuple()) -> None: + """Override settings in `app` with those in ENVVARS""" + for setting in (key for key in app.config if key not in ignore): + app.config[setting] = os.environ.get(setting) or app.config[setting] + +def setup_logging_handlers(app: Flask) -> None: + """Setup the loggging handlers.""" + stderr_handler = logging.StreamHandler(stream=sys.stderr) + app.logger.addHandler(stderr_handler) + + root_logger = logging.getLogger() + root_logger.addHandler(stderr_handler) + root_logger.setLevel(app.config["LOGLEVEL"]) + +def create_app(config: dict = {}) -> Flask: + """Create and return a new flask application.""" + app = Flask(__name__) + + # ====== Setup configuration ====== + app.config.from_object(settings) # Default settings + # Override defaults with startup settings + app.config.update(config) + # Override app settings with site-local settings + if "GN_AUTH_CONF" in os.environ: + app.config.from_envvar("GN_AUTH_CONF") + + override_settings_with_envvars(app) + # ====== END: Setup configuration ====== + + check_mandatory_settings(app) + + setup_logging_handlers(app) + + return app |