Auth0ConnectionEx.psm1

class Auth0Token
{
    [ValidateNotNullOrEmpty()][string]$access_token
    [ValidateNotNullOrEmpty()][string]$token_type
    [int]$expires_in
    [string[]]$scope
}

class Auth0Context
{
    [ValidateNotNullOrEmpty()][string]$Domain
    [ValidateNotNullOrEmpty()][Auth0Token]$Token
}

function Get-Auth0Context
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, Position=1)] [string] $Domain,
        [Parameter(Mandatory=$true, Position=2)] [string] $ClientId,
        [Parameter(Mandatory=$true, Position=3)] [string] $ClientSecret
    )

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add('Content-Type', 'application/json')
    $json = @{
        'client_id' = $ClientId
        'client_secret' = $ClientSecret
        'audience' = "https://$Domain/api/v2/"
        'grant_type' = 'client_credentials'
    } | ConvertTo-Json

    $result = $webClient.UploadString("https://$Domain/oauth/token", $json) | ConvertFrom-Json
    return [Auth0Context]@{
        Domain = $Domain
        Token = [Auth0Token]$result
    }
}

function Search-Auth0Connection {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true, Position=1)] [Auth0Context] $Context,
        [parameter(Mandatory=$true, Position=2)] [String] $Name = ''
    )

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add('Authorization', $Context.Token.token_type + ' ' + $Context.Token.access_token)    
    return $webClient.DownloadString('https://' + $Context.Domain + '/api/v2/connections?per_page=1&page=0&name=' + $Name) | ConvertFrom-Json    
}

function Remove-Auth0Connection
{
    [CmdletBinding()]
    param (
        [Parameter(Mandatory=$true, Position=1)] [Auth0Context] $Context,
        [Parameter(Mandatory=$true, Position=2, ValueFromPipelineByPropertyName)]
        [Alias('id')] [string] $ConnectionId
    )

    $webClient = New-Object System.Net.WebClient
    $webClient.Headers.Add('Authorization', $Context.Token.token_type + ' ' + $Context.Token.access_token)
    $content = New-Object System.Collections.Specialized.NameValueCollection
    return $webClient.UploadValues('https://' + $Context.Domain + '/api/v2/connections/' + $ConnectionId, 'DELETE', $content) | ConvertFrom-Json
}