{#
# This file gets imported to configure forward auth in handlers.
# - Section: Reverse Proxy Configurations
#}
{% if generalSettings.AuthProvider %}
    {# Check if the domain is IPv6 and wrap in square brackets if necessary #}
    {% set is_ipv6 = (':' in generalSettings.AuthToDomain and generalSettings.AuthToDomain.count(':') >= 2) %}
    {% set auth_url = (generalSettings.AuthToTls|default("0") == "1" and 'https://' or 'http://') + (is_ipv6 and '[' or '') + generalSettings.AuthToDomain|default("") + (is_ipv6 and ']' or '') + (generalSettings.AuthToPort and ':' + generalSettings.AuthToPort or '') %}
{% endif %}
{% macro generate_copy_headers() %}
    {% if generalSettings.CopyHeaders %}
        {% for header_uuid in generalSettings.CopyHeaders.split(',') %}
            {% set header = helpers.toList('Pischem.caddy.reverseproxy.header') | selectattr('@uuid', 'equalto', header_uuid) | first %}
            {% if header and header.HeaderType %}
                copy_headers {{ header.HeaderType }}
            {% endif %}
        {% endfor %}
    {% endif %}
{% endmacro %}
{% if generalSettings.AuthProvider == 'authelia' %}
    forward_auth {{ auth_url }} {
    {% if generalSettings.AuthToUri %}
        uri {{ generalSettings.AuthToUri|default("") }}
    {% endif %}
        copy_headers Remote-User
        copy_headers Remote-Groups
        copy_headers Remote-Name
        copy_headers Remote-Email
        {{ generate_copy_headers() }}
    }
{% elif generalSettings.AuthProvider == 'authentik' %}
    reverse_proxy /outpost.goauthentik.io/* {{ auth_url }} {
    {% if generalSettings.AuthToTls|default("0") == "1" %}
        header_up Host {http.reverse_proxy.upstream.hostport}
    {% endif %}
    }
    forward_auth {{ auth_url }} {
    {% if generalSettings.AuthToUri %}
        uri {{ generalSettings.AuthToUri|default("") }}
    {% endif %}
        copy_headers X-Authentik-Username
        copy_headers X-Authentik-Groups
        copy_headers X-Authentik-Email
        copy_headers X-Authentik-Name
        copy_headers X-Authentik-Uid
        copy_headers X-Authentik-Jwt
        copy_headers X-Authentik-Meta-Jwks
        copy_headers X-Authentik-Meta-Outpost
        copy_headers X-Authentik-Meta-Provider
        copy_headers X-Authentik-Meta-App
        copy_headers X-Authentik-Meta-Version
        {{ generate_copy_headers() }}
    }
{% endif %}
