---
apiVersion: v1
kind: ConfigMap
metadata:
  name: kubernetes-dashboard-oidc-config
  namespace: kube-system
data:
  nginx.conf: |-
    events {
      worker_connections 128;
    }
    error_log /dev/stdout debug;

    env OIDC_CLIENT_ID;
    env OIDC_CLIENT_SECRET;

    http {
      resolver 8.8.8.8;

      lua_ssl_trusted_certificate /etc/ssl/certs/ca-certificates.crt;
      lua_ssl_verify_depth 5;

      # cache for discovery metadata documents
      lua_shared_dict discovery 1m;
      # cache for JWKs
      lua_shared_dict jwks 1m; 

      server {
        listen 9000;
        large_client_header_buffers 4 32k;

        location / {
          access_by_lua_block {
            local opts = {
              redirect_uri_path = "/oauth2/callback",
              discovery = "{{ .oidcClientURL }}/.well-known/openid-configuration",
              client_id = os.getenv("OIDC_CLIENT_ID"),
              client_secret = os.getenv("OIDC_CLIENT_SECRET"),
              session_contents = {id_token=true,enc_id_token=true,access_token=true}
            }

            local res, err, _target, session = require("resty.openidc").authenticate(opts)

            if err or not res then
              ngx.status = 403
              ngx.say("forbidden")
              ngx.exit(ngx.HTTP_FORBIDDEN)
            end
          
            ngx.req.set_header("Authorization", "Bearer "..session.data.enc_id_token)
          }

          proxy_pass {{ .backendServerURL }};
          proxy_ssl_verify off;
          proxy_ssl_server_name on;
        }
      }
    }
