authentik.lib.utils.reflection

authentik lib reflection utilities

 1"""authentik lib reflection utilities"""
 2
 3import os
 4from importlib import import_module
 5from pathlib import Path
 6from tempfile import gettempdir
 7
 8from django.conf import settings
 9from django.utils.module_loading import import_string
10from structlog.stdlib import get_logger
11
12from authentik.lib.config import CONFIG
13
14SERVICE_HOST_ENV_NAME = "KUBERNETES_SERVICE_HOST"
15LOGGER = get_logger()
16
17
18def all_subclasses[T: type](cls: T, sort=True) -> list[T] | set[T]:
19    """Recursively return all subclasses of cls"""
20    classes = set(cls.__subclasses__()).union(
21        [s for c in cls.__subclasses__() for s in all_subclasses(c, sort=sort)]
22    )
23    # Check if we're in debug mode, if not exclude classes which have `__debug_only__`
24    if not settings.DEBUG:
25        # Filter class out when __debug_only__ is not False
26        classes = [x for x in classes if not getattr(x, "__debug_only__", False)]
27        # classes = filter(lambda x: not getattr(x, "__debug_only__", False), classes)
28    if sort:
29        return sorted(classes, key=lambda x: x.__name__)
30    return classes
31
32
33def class_to_path(cls: type) -> str:
34    """Turn Class (Class or instance) into module path"""
35    return f"{cls.__module__}.{cls.__name__}"
36
37
38def path_to_class(path: str = "") -> type:
39    """Import module and return class"""
40    parts = path.split(".")
41    package = ".".join(parts[:-1])
42    _class = getattr(import_module(package), parts[-1])
43    return _class
44
45
46def get_apps():
47    """Get list of all authentik apps"""
48    from django.apps.registry import apps
49
50    for _app in apps.get_app_configs():
51        if _app.name.startswith("authentik"):
52            yield _app
53
54
55def get_env() -> str:
56    """Get environment in which authentik is currently running"""
57    if "CI" in os.environ:
58        return "ci"
59    if CONFIG.get_bool("debug"):
60        return "dev"
61    if SERVICE_HOST_ENV_NAME in os.environ:
62        return "kubernetes"
63    if (Path(gettempdir()) / "authentik-mode").exists():
64        return "compose"
65    if "AK_APPLIANCE" in os.environ:
66        return os.environ["AK_APPLIANCE"]
67    return "custom"
68
69
70def ConditionalInheritance(path: str):
71    """Conditionally inherit from a class, intended for things like authentik.enterprise,
72    without which authentik should still be able to run"""
73    try:
74        cls = import_string(path)
75        return cls
76    except ModuleNotFoundError:
77        LOGGER.warning("Unable to import", path=path)
78        return type(path.rsplit(".", 1)[-1], (), {})
SERVICE_HOST_ENV_NAME = 'KUBERNETES_SERVICE_HOST'
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def all_subclasses(cls: T, sort=True) -> list[T] | set[T]:
19def all_subclasses[T: type](cls: T, sort=True) -> list[T] | set[T]:
20    """Recursively return all subclasses of cls"""
21    classes = set(cls.__subclasses__()).union(
22        [s for c in cls.__subclasses__() for s in all_subclasses(c, sort=sort)]
23    )
24    # Check if we're in debug mode, if not exclude classes which have `__debug_only__`
25    if not settings.DEBUG:
26        # Filter class out when __debug_only__ is not False
27        classes = [x for x in classes if not getattr(x, "__debug_only__", False)]
28        # classes = filter(lambda x: not getattr(x, "__debug_only__", False), classes)
29    if sort:
30        return sorted(classes, key=lambda x: x.__name__)
31    return classes

Recursively return all subclasses of cls

def class_to_path(cls: type) -> str:
34def class_to_path(cls: type) -> str:
35    """Turn Class (Class or instance) into module path"""
36    return f"{cls.__module__}.{cls.__name__}"

Turn Class (Class or instance) into module path

def path_to_class(path: str = '') -> type:
39def path_to_class(path: str = "") -> type:
40    """Import module and return class"""
41    parts = path.split(".")
42    package = ".".join(parts[:-1])
43    _class = getattr(import_module(package), parts[-1])
44    return _class

Import module and return class

def get_apps():
47def get_apps():
48    """Get list of all authentik apps"""
49    from django.apps.registry import apps
50
51    for _app in apps.get_app_configs():
52        if _app.name.startswith("authentik"):
53            yield _app

Get list of all authentik apps

def get_env() -> str:
56def get_env() -> str:
57    """Get environment in which authentik is currently running"""
58    if "CI" in os.environ:
59        return "ci"
60    if CONFIG.get_bool("debug"):
61        return "dev"
62    if SERVICE_HOST_ENV_NAME in os.environ:
63        return "kubernetes"
64    if (Path(gettempdir()) / "authentik-mode").exists():
65        return "compose"
66    if "AK_APPLIANCE" in os.environ:
67        return os.environ["AK_APPLIANCE"]
68    return "custom"

Get environment in which authentik is currently running

def ConditionalInheritance(path: str):
71def ConditionalInheritance(path: str):
72    """Conditionally inherit from a class, intended for things like authentik.enterprise,
73    without which authentik should still be able to run"""
74    try:
75        cls = import_string(path)
76        return cls
77    except ModuleNotFoundError:
78        LOGGER.warning("Unable to import", path=path)
79        return type(path.rsplit(".", 1)[-1], (), {})

Conditionally inherit from a class, intended for things like authentik.enterprise, without which authentik should still be able to run