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 [Alias("LicenseId")] [Parameter(Mandatory = $true)] $LicenseKey, [Parameter(Mandatory = $false)] $certificate, [Parameter(Mandatory = $false)] [ValidateSet("prod", "dev", "local", "preview")] $environment = 'prod' ) Try { $script:apiBaseUrl = "api.insight.ctglobalapp.com" $scopes = @("api://3690266a-3ae2-4ff2-9a0d-949bc76d4ca7/.default") $tenantId = "558b59a5-e432-4d65-a2b1-ac3bf80649d8"; $certificateName = "CN=CTGlobal IA Sync"; switch ($environment) { "local" { $script:apiBaseUrl = "localhost:5001" } "dev" { $script:apiBaseUrl = "api.dev.insight.ctglobalapp.com" $scopes = @("api://d418dd0a-1802-4f50-9f81-97e023203e5f/.default") } "preview"{ $script:apiBaseUrl = "iapreview-backend-public-we-tst.azurewebsites.net" $scopes = @("api://d418dd0a-1802-4f50-9f81-97e023203e5f/.default") $certificateName = "CN=CTGlobal IA Admin" $script:AppId = "895b0675-a676-4384-80e7-80f5e39fe5eb" } } $clientId = $LicenseKey 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 if($environment -eq "preview"){ Set-IATenantHeader -TenantId "558d1d63-c264-45dc-b8bc-6441dd3926ac" #CTGlobal Dev Tenant } } 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 $_ } } } |