Functions/Connect-IA.ps1

Function Connect-IA {
    <#
        .SYNOPSIS
            This is used to connect to the Insight Analytics API.
        .DESCRIPTION
            This function is used to authenticate to the IA API. This will grant you a secure connection to run the different functions in the CTGlobal Insight Analytics Customer Powershell Module.
        .EXAMPLE
            $ConnectorId = "b6eabcb6-c164-40a0-a2af-4617a8fa06bf"
            Connect-IA -connectorId $ConnectorId -environment prod
    #>

    Param(
        #ConnectorId is used to authenticate with the backend and filter tenant
        [Parameter(Mandatory = $true)]
        $LicenseId, 
        #Optional: Send certificate file in via parameter (for Azure Automation support)
        [Parameter(Mandatory = $false)]
        $certificate,
        #Optional: Used for testing purposes
        [Parameter(Mandatory = $false)]
        [ValidateSet("prod", "dev", "local")]
        $environment = 'prod'
    ) 
    
    Try {
        $script:apiBaseUrl = "api.insight.ctglobalapp.com"
        $scopes = @("api://3690266a-3ae2-4ff2-9a0d-949bc76d4ca7/.default")
        switch ($environment) {
            "local" {
                $script:apiBaseUrl = "localhost:5001"
            }
            "dev" {
                $script:apiBaseUrl = "api.dev.insight.ctglobalapp.com"
                $scopes = @("api://d418dd0a-1802-4f50-9f81-97e023203e5f/.default")
            }
        }

        $tenantId = "558b59a5-e432-4d65-a2b1-ac3bf80649d8";
        $certificateName = "CN=CTGlobal IA Sync";

        $clientId = $LicenseId

        if ($null -eq $certificate) {

            Write-Output 'Authenticating...'
            $clientMSAL = New-Object -TypeName "IA.Standard.Library.Authentication.Clients.MSAL" -ArgumentList $tenantId, $null, $certificateName, $clientId, $scopes
            $clientMSAL.Connect().Wait()
            
            if($clientMSAL.AuthResult.AccessToken){
                Write-Output "Authentication successful, expires on: $($clientMsal.AuthResult.ExpiresOn.LocalDateTime)"
            } 
        }
        else {
            $clientMSAL = New-Object -TypeName "IA.Standard.Library.Authentication.Clients.MSAL" -ArgumentList $tenantId, $clientId, $scopes
            $clientMSAL.Connect($certificate).Wait()
    
        }
        
        $script:Headers = @{
            "Authorization" = "Bearer $($clientMSAL.AccessToken)"
        }
        $script:clientMSAL = $clientMSAL
    }
    catch {
        $currentError = $_

        if($currentError.Exception.InnerException.InnerExceptions -like '*Keyset does not exist*'){
            throw [System.AccessViolationException]::New('IA Sync Certificate Missing!', $currentError.Exception)
        }

        if ($currentError.Exception.InnerException.InnerExceptions) {
            throw "Error, Exceptions:`n$($currentError.Exception.InnerException.InnerExceptions)"
        }
        else {
            throw $_
        }
    }
}