# include allow method filtering
if ($request_method !~ ^(GET|OPTIONS|POST)$) {
	return 405;
}

location /adfs/ls {
	proxy_pass  https://idp_backend;
	proxy_set_header Host ${NGX_IDP_HOSTNAME};
	proxy_redirect https://${NGX_IDP_HOSTNAME} https://${NGX_PRXY_IDP_HOSTNAME};
	proxy_ssl_server_name on;
    proxy_ssl_name ${NGX_IDP_HOSTNAME};
	proxy_no_cache 1;
	proxy_cache_bypass 1;

	# add duplicate cookie on the root domain
	# Note: If we have two reverse proxyies proxying IDP, when failing to otherside the second reverse proxy IDP 
	# will not have the cookie stored from primary RP IDP when it is stored on the domain name of RP IDP
	# Storting it in root domain will be accessible for the other RP IDP as well.
	header_filter_by_lua_block {
		local function get_root_domain(hostname)
			local root_domain = hostname:match("[^.]+%.([^.]+%.[^.]+)$")
			return root_domain or hostname
		end

		local root_domain = get_root_domain(ngx.var.host)
		local new_cookies = {}
		local cookies = ngx.header["Set-Cookie"]

		if cookies then
			local function duplicate_cookie_with_new_domain(cookie)
				local modified_cookie = cookie .. "; Domain=." .. root_domain .. "; Secure; HttpOnly; SameSite=None"
				table.insert(new_cookies, modified_cookie)
			end

			if type(cookies) == "table" then
				for _, cookie in ipairs(cookies) do
					local cookie_with_new_domain = string.gsub(cookie, "Domain=[^;]+", "Domain=." .. root_domain)
					table.insert(new_cookies, cookie_with_new_domain)
					duplicate_cookie_with_new_domain(cookie)
				end
			else
				local cookie_with_new_domain = string.gsub(cookies, "Domain=[^;]+", "Domain=." .. root_domain)
				table.insert(new_cookies, cookie_with_new_domain)
				duplicate_cookie_with_new_domain(cookies)
			end
			ngx.header["Set-Cookie"] = new_cookies
		end
	}
}



location / {

    proxy_ssl_server_name on;
    proxy_ssl_name ${NGX_IDP_HOSTNAME};
    proxy_set_header Host ${NGX_IDP_HOSTNAME};
    proxy_redirect https://${NGX_IDP_HOSTNAME} https://${NGX_PRXY_IDP_HOSTNAME};
	proxy_pass https://idp_backend;
	proxy_no_cache 1;
	proxy_cache_bypass 1;
	
	add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload";
}
