Private/Invoke-GhostOwnerRequest.ps1
|
function Invoke-GhostOwnerRequest { <# .SYNOPSIS Sends a request to the Admin API of a local site as its owner and returns the parsed response. .DESCRIPTION Start-GhostLocalSite sets a site up with this: creating the owner and the integration, activating a theme and uploading routes are things Ghost only lets a signed-in person do, not an integration with an Admin API key. Everything else in the module goes through Submit-Request, with a key. The owner is signed in with a session cookie, which the web session keeps. Ghost only accepts such a request when it comes from the site itself, which the Origin header says. A failed request stops with the message Ghost returned. .EXAMPLE Invoke-GhostOwnerRequest -SiteUrl 'http://localhost:2368' -Resource '/integrations/' -Session $session Returns the integrations of the site, once the session is signed in. #> [CmdletBinding()] [OutputType([pscustomobject])] param( # Address of the site, such as http://localhost:2368. [Parameter(Mandatory)] [string] $SiteUrl, # Path below /ghost/api/admin, such as /integrations/. [Parameter(Mandatory)] [string] $Resource, # The HTTP method. [string] $Method = 'Get', # The body of the request. It is sent as JSON. [System.Collections.IDictionary] $Body, # The body of a request that is not JSON, such as the form of an upload, as bytes. Needs -ContentType. [byte[]] $Content, # The content type of -Content. [string] $ContentType, # The web session that holds the cookie of the owner. [Parameter(Mandatory)] [Microsoft.PowerShell.Commands.WebRequestSession] $Session ) $request = @{ Uri = '{0}/ghost/api/admin{1}' -f $SiteUrl, $Resource Method = $Method Headers = @{ Origin = $SiteUrl } WebSession = $Session UseBasicParsing = $true } if ($Body) { # Bytes, because Windows PowerShell does not send a string body as UTF-8. $request['Body'] = [System.Text.Encoding]::UTF8.GetBytes((ConvertTo-Json -InputObject $Body -Depth 10)) $request['ContentType'] = 'application/json; charset=utf-8' } elseif ($Content) { $request['Body'] = $Content $request['ContentType'] = $ContentType } try { Invoke-RestMethod @request } catch { $detail = $_.Exception.Message if ($_.ErrorDetails -and $_.ErrorDetails.Message) { try { $reported = @((ConvertFrom-Json -InputObject $_.ErrorDetails.Message).errors)[0] $detail = @($reported.message, $reported.context) -join ' ' } catch { Write-Debug -Message "The error response is not a Ghost error: $($_.Exception.Message)" } } throw ('Ghost refused {0} {1}: {2}' -f $Method.ToUpperInvariant(), $Resource, $detail.Trim()) } } |