From 7a96e7782a11f766cae99bdd26210c91b0fcb73d Mon Sep 17 00:00:00 2001 From: Stephan Yelle Date: Tue, 27 May 2025 00:04:25 -0400 Subject: [PATCH] Update testTaskGate.ps1 --- testTaskGate.ps1 | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/testTaskGate.ps1 b/testTaskGate.ps1 index 00c237c..aa33eb2 100644 --- a/testTaskGate.ps1 +++ b/testTaskGate.ps1 @@ -210,41 +210,55 @@ function Handle-FetchSites { Write-Host "[Debug] Handle-FetchSites invoked" try { - $body = (New-Object IO.StreamReader $Context.Request.InputStream).ReadToEnd() - $pw = (ConvertFrom-Json $body).password + # Safely read the JSON body using UTF8 + $reader = New-Object System.IO.StreamReader($Context.Request.InputStream, [System.Text.Encoding]::UTF8) + $body = $reader.ReadToEnd() + Write-Host "[Debug] Raw body: $body" - # Securely get Datto API credentials + # Parse JSON and extract password + $json = $body | ConvertFrom-Json + $pw = $json.password + Write-Host "[Debug] Parsed password: $pw" + + if (-not $pw) { + Write-Host "[Error] Password is missing from request body" + $Context.Response.StatusCode = 400 + $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) + return + } + + # Call credential helper $creds = Get-DattoApiCredentials -Password $pw - if (-not $creds) { - Write-LogHybrid "Failed to fetch credentials." "Error" "Server" + Write-Host "[Error] Credential fetch failed" $Context.Response.StatusCode = 500 $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) return } - # Fetch the site list using the helper + # Fetch site list from Datto API $sites = Install-DattoRMM-Helper ` - -ApiUrl $creds.ApiUrl ` - -ApiKey $creds.ApiKey ` + -ApiUrl $creds.ApiUrl ` + -ApiKey $creds.ApiKey ` -ApiSecretKey $creds.ApiSecretKey ` -FetchSitesOnly if (-not $sites) { + Write-Host "[Error] Site list was empty or failed to fetch" $Context.Response.StatusCode = 500 $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) return } - # Serialize and respond - $json = $sites | ConvertTo-Json -Depth 2 - $bytes = [Text.Encoding]::UTF8.GetBytes($json) - $Context.Response.ContentType = "application/json" + # Return site list as JSON + $jsonSites = $sites | ConvertTo-Json -Depth 2 + $bytes = [Text.Encoding]::UTF8.GetBytes($jsonSites) + $Context.Response.ContentType = "application/json" $Context.Response.ContentLength64 = $bytes.Length $Context.Response.OutputStream.Write($bytes, 0, $bytes.Length) } catch { - # Write-LogHybrid -Message "Handle-FetchSites failed: $($_.Exception.Message)" -Level "Error" -TaskCategory "Server" -LogToEvent:$true + Write-Host "[Exception] $($_.Exception.Message)" $Context.Response.StatusCode = 500 $Context.Response.OutputStream.Write([Text.Encoding]::UTF8.GetBytes("[]"), 0, 2) } finally { @@ -254,6 +268,8 @@ function Handle-FetchSites { + + # On-boarding handlers function Set-SVSPowerPlan { param($Context)