# Authentik Configuration - Grafana SSO Integration
# Generated: 2025-09-20 07:25:00
# This file contains the Authentik configuration for Grafana OAuth2/OIDC integration
# Apply this blueprint to automate the setup of Grafana SSO with Authentik

version: 1

metadata:
  name: AI Tax Agent Grafana SSO Integration
  labels:
    blueprints.goauthentik.io/generated: "true"

entries:
  # Grafana OAuth2 Provider
  - attrs:
      authorization_flow: !Find [authentik_flows.flow, [slug, default-provider-authorization-implicit-consent]]
      invalidation_flow: !Find [authentik_flows.flow, [slug, default-provider-invalidation-flow]]
      name: grafana
      client_type: confidential
      client_id: grafana
      client_secret: ${AUTHENTIK_GRAFANA_CLIENT_SECRET:-changeme-grafana-secret}
      redirect_uris: 
        - https://grafana.${DOMAIN:-local.lan}/login/generic_oauth
      sub_mode: hashed_user_id
      include_claims_in_id_token: true
      issuer_mode: per_provider
      signing_key: !Find [authentik_crypto.certificatekeypair, [name, authentik Self-signed Certificate]]
      property_mappings:
        - !Find [authentik_providers_oauth2.scopemapping, [scope_name, openid]]
        - !Find [authentik_providers_oauth2.scopemapping, [scope_name, email]]
        - !Find [authentik_providers_oauth2.scopemapping, [scope_name, profile]]
        - !KeyOf grafana-groups-mapping
    conditions: []
    identifiers:
      name: grafana
    model: authentik_providers_oauth2.oauth2provider
    permissions: []
    state: present

  # Custom Groups Mapping for Grafana
  - attrs:
      name: Grafana Groups Mapping
      description: Maps Authentik groups to Grafana roles
      scope_name: groups
      expression: |
        # Map Authentik groups to Grafana roles
        groups = []
        user_groups = [group.name for group in request.user.ak_groups.all()]
        
        # Admin role mapping
        if "authentik Admins" in user_groups or "Administrators" in user_groups:
            groups.append("Admin")
        
        # Editor role mapping  
        if "Tax Reviewers" in user_groups or "Accountants" in user_groups:
            groups.append("Editor")
        
        # Viewer role mapping (default for all authenticated users)
        groups.append("Viewer")
        
        return {
            "groups": groups,
            "role": groups[0] if groups else "Viewer"  # Primary role
        }
    conditions: []
    identifiers:
      name: Grafana Groups Mapping
    model: authentik_providers_oauth2.scopemapping
    permissions: []
    state: present

  # Grafana Application
  - attrs:
      name: Grafana
      slug: grafana
      provider: !KeyOf grafana
      policy_engine_mode: any
      meta_description: Grafana monitoring and observability platform
      meta_publisher: Grafana Labs
    conditions: []
    identifiers:
      slug: grafana
    model: authentik_core.application
    permissions: []
    state: present
