Public/Authorization/Connect-AspireAPI.ps1

# Global variables to store the authentication token and refresh token
$script:AspireToken = $null
$script:AspireRefreshToken = $null
$script:BaseUrl = "https://cloud-api.youraspire.com"

<#
.SYNOPSIS
    Connects to the Aspire API using client credentials and retrieves a Bearer token and refresh token.
.DESCRIPTION
    Posts ClientId and Secret to the /Authorization endpoint to obtain a token and refresh token.
    If a refresh token is cached, it will use the /Authorization/RefreshToken endpoint instead.
.PARAMETER ClientId
    The client ID for authentication (optional if refresh token is cached).
.PARAMETER Secret
    The client secret for authentication (optional if refresh token is cached).
.EXAMPLE
    Connect-AspireAPI -ClientId "your-client-id" -Secret "your-secret"
.EXAMPLE
    Connect-AspireAPI # Uses cached refresh token if available
#>

function Connect-AspireAPI {
    [CmdletBinding()]
    param(
        [string]$ClientId,
        [string]$Secret
    )

    $headers = @{
        'Content-Type' = 'application/json'
    }

    try {
        if ($ClientId -and $Secret) {
            # Initial authentication using /Authorization
            $authBody = @{
                ClientId = $ClientId
                Secret = $Secret
            } | ConvertTo-Json

            $uri = "$script:BaseUrl/Authorization"
            $response = Invoke-RestMethod -Uri $uri -Method Post -Body $authBody -Headers $headers
        } elseif ($script:AspireRefreshToken) {
            # Token refresh using /Authorization/RefreshToken
            $authBody = @{
                RefreshToken = $script:AspireRefreshToken
            } | ConvertTo-Json

            $uri = "$script:BaseUrl/Authorization/RefreshToken"
            $response = Invoke-RestMethod -Uri $uri -Method Post -Body $authBody -Headers $headers
        } else {
            Write-Error "No ClientId/Secret provided and no cached refresh token."
            return
        }

        # Store token and refresh token
        $script:AspireToken = $response.Token
        $script:AspireRefreshToken = $response.RefreshToken
        Write-Output "Successfully authenticated. Token retrieved."
    } catch {
        Write-Error "Authentication failed: $($_.Exception.Message)"
    }
}