Skip to content
Snippets Groups Projects
security.py 1.36 KiB
"""Module for initializing OAuth client credentials and OIDC user."""

from authlib.integrations.starlette_client import OAuth
from nwastdlib.url import URL

from gso.auth.oidc_policy_helper import HTTPX_SSL_CONTEXT, OIDCUser, opa_decision
from gso.auth.settings import oauth2_settings

oauth_client_credentials = OAuth()

well_known_endpoint = URL(oauth2_settings.OIDC_CONF_WELL_KNOWN_URL)

oauth_client_credentials.register(
    "connext",
    server_metadata_url=well_known_endpoint / ".well-known" / "openid-configuration",
    client_id=oauth2_settings.OAUTH2_RESOURCE_SERVER_ID,
    client_secret=oauth2_settings.OAUTH2_RESOURCE_SERVER_SECRET,
    request_token_params={"grant_type": "client_credentials"},
    client_kwargs={"verify": HTTPX_SSL_CONTEXT},
)

oidc_user = OIDCUser(
    oauth2_settings.OIDC_CONF_WELL_KNOWN_URL,
    oauth2_settings.OAUTH2_RESOURCE_SERVER_ID,
    oauth2_settings.OAUTH2_RESOURCE_SERVER_SECRET,
)

opa_security_default = opa_decision(oauth2_settings.OPA_URL, oidc_user)


def get_oidc_user() -> OIDCUser:
    """Retrieve the global OIDCUser instance.

    This function returns the instance of OIDCUser initialized in the module.
    It is typically used for accessing the OIDCUser across different parts of the application.

    Returns
    -------
        OIDCUser: The instance of OIDCUser configured with OAuth2 settings.
    """
    return oidc_user