Public/Connection.ps1



<#
.SYNOPSIS
    Connects to HelloId
.DESCRIPTION
    Connect-HelloId connects you to HelloId and saves the connection info for use with other PSHelloId cmdlets, enabling you to run those without specifying companyname, apikey and apisecret for every cmdlet
.PARAMETER CompanyName
    The companyname that's used in the helloId URL. Required to know which HelloID tenant to talk to
.PARAMETER ApiKey
    The Apikey to use for the api call
.PARAMETER ApiSecret
    The Apisecret belonging to the apikey, has to be a securestring
.EXAMPLE
    Connect-HelloId -CompanyName "MyCompany" -ApiKey "myapikey" -ApiSecret (ConvertTo-SecureString -AsPlainText -String "password" -Force)
 
    Connects you with the specified keys to the company environment
 
.OUTPUTS
    An object that represents your company environment and the api key
#>



function Connect-HelloId {
    [CmdletBinding()]
    param (
        # Company name used in the URL
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$CompanyName,
      
        # Api key
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [string]$ApiKey,
  
        # Api secret
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [securestring]$ApiSecret,

        # For preview tenants
        [Parameter(Mandatory = $false)]
        [switch]$IsPreviewTenant
    )


    #Create credential object for authentication
    $Cred = New-Object System.Management.Automation.PSCredential ($ApiKey, $ApiSecret)

    #Headers
    $headers = @{
        "Content-Type" = "application/json"
    }
    
    if ($IsPreviewTenant){
        $BaseUrl = "https://$CompanyName.preview-helloid.com"
    }
    else {
        $BaseUrl = "https://$CompanyName.helloid.com"
    }
    $URI = "$BaseUrl/api/v1/automation/variables"
    
    $output = Invoke-RestMethod -Uri $URI -Method "GET" -Headers $headers -Credential $Cred -UseBasicParsing
    
    if ($output.count -ge 2) {
        $Global:HelloIdConnection = "" | Select-Object -Property CompanyName,BaseUrl,ApiKey,ApiCredentials
        $Global:HelloIdConnection.CompanyName = $CompanyName
        $Global:HelloIdConnection.BaseUrl = $BaseUrl
        $Global:HelloIdConnection.ApiKey = $ApiKey
        $Global:HelloIdConnection.ApiCredentials = $Cred
        
        Set-Variable -Name HelloIdConnection -Option ReadOnly

        Write-Output $Global:HelloIdConnection | Select-Object -Property CompanyName,BaseUrl,ApiKey
    }
    else {
        throw "Failed to connect to HelloId"
    }
}