Auth0ConnectionEx.psm1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
}