Newer
Older
gn-synapse / app / auth / client.py
"""Сборка единственного на процесс gnexus-gauth клиента (SSO + валидация токенов)."""

from functools import lru_cache

import httpx
from gnexus_gauth.client import GAuthClient
from gnexus_gauth.config import GAuthConfig
from gnexus_gauth.oauth import HttpTokenEndpoint
from gnexus_gauth.runtime import HttpRuntimeUserProvider
from gnexus_gauth.support import SystemClock
from gnexus_gauth.webhook import HmacWebhookVerifier, JsonWebhookParser

from app.auth.stores import RedisPkceStore, RedisStateStore
from app.config import Settings, get_settings

# Scopes полного userinfo: системная роль + клиентские роли/права + профиль.
GAUTH_SCOPES = ["openid", "email", "profile", "roles", "permissions"]


def build_gauth(config: Settings) -> GAuthClient:
    gconf = GAuthConfig(
        base_url=config.gauth_base_url,
        client_id=config.gauth_client_id,
        client_secret=config.gauth_client_secret,
        redirect_uri=config.gauth_redirect_uri,
        user_agent="gnexus-synapse",
    )
    # gnexus-auth в LAN живёт за self-signed TLS — verify отключается через env.
    http = httpx.Client(verify=config.gauth_verify_tls)
    return GAuthClient(
        config=gconf,
        token_endpoint=HttpTokenEndpoint(gconf, http),
        runtime_user_provider=HttpRuntimeUserProvider(gconf, http),
        webhook_verifier=HmacWebhookVerifier(gconf),
        webhook_parser=JsonWebhookParser(),
        state_store=RedisStateStore(),
        pkce_store=RedisPkceStore(),
        clock=SystemClock(),
    )


@lru_cache
def get_gauth_client() -> GAuthClient:
    return build_gauth(get_settings())