diff --git a/testTaskGate.ps1 b/testTaskGate.ps1 index 47eeafe..e47f474 100644 --- a/testTaskGate.ps1 +++ b/testTaskGate.ps1 @@ -210,32 +210,45 @@ function Handle-FetchSites { Write-Host "[Debug] Handle-FetchSites invoked" try { - $body = (New-Object IO.StreamReader $Context.Request.InputStream).ReadToEnd() + $body = (New-Object IO.StreamReader $Context.Request.InputStream).ReadToEnd() $pw = (ConvertFrom-Json $body).password + # Securely get Datto API credentials $creds = Get-DattoApiCredentials -Password $pw + if (-not $creds) { - Write-LogHybrid "Credential fetch failed." "Error" - $Context.Response.StatusCode = 403 - Respond-JSON $Context @() + Write-LogHybrid "Failed to fetch credentials." "Error" "Server" + $Context.Response.StatusCode = 500 + $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) return } + # Fetch the site list using the helper $sites = Install-DattoRMM-Helper ` - -ApiUrl $creds.ApiUrl ` - -ApiKey $creds.ApiKey ` - -ApiSecretKey $creds.ApiSecretKey ` - -FetchSitesOnly + -ApiUrl $creds.ApiUrl ` + -ApiKey $creds.ApiKey ` + -ApiSecretKey $creds.ApiSecretKey ` + -FetchSitesOnly if (-not $sites) { $Context.Response.StatusCode = 500 - $sites = @() + $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) + return } - Respond-JSON $Context $sites + # Serialize and respond + $json = $sites | ConvertTo-Json -Depth 2 + $bytes = [Text.Encoding]::UTF8.GetBytes($json) + $Context.Response.ContentType = "application/json" + $Context.Response.ContentLength64 = $bytes.Length + $Context.Response.OutputStream.Write($bytes, 0, $bytes.Length) + } catch { + Write-LogHybrid "Handle-FetchSites failed: $($_.Exception.Message)" "Error" "Server" $Context.Response.StatusCode = 500 - Respond-JSON $Context @() + $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) + } finally { + $Context.Response.OutputStream.Close() } }