Public/Authentication/Get-PopuliToken.ps1

function Get-PopuliToken
{
    [CmdletBinding(PositionalBinding=$true)]
    param
    (
        [Parameter(Mandatory=$true)][pscredential]$Credential,
        [Parameter(Mandatory=$true)][ValidatePattern('^(?i)https:\/\/\S+\.populiweb\.com\/?$')][string]$BaseUrl
    )

    try
    {

        [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

        if ($BaseUrl -match '\/$')
        {
            $BaseUrl = $BaseUrl -replace '\/$'
        }

        $body = @{
            username = $Credential.UserName
            password = $Credential.GetNetworkCredential().Password
        }

    
        $response = Invoke-RestMethod -Uri "$BaseUrl/api/" -Method POST -ContentType 'application/x-www-form-urlencoded' -Body $body

        $env:PopuliBaseUrl = $BaseUrl
        $env:PopuliToken = $response.response.access_key
        $env:PopuliAccountId = $response.response.accountId
        $env:PopuliAccountType = $response.response.accountType

        Write-Log "Connected to Populi API OK!"

        return $env:PopuliToken
    }
    catch
    {
        Write-Log "Error in Get-PopuliToken" -LogType: error -ErrorObject $_

        $errDetail = $ErrorObject.ErrorDetails.Message -replace '\r|\n', ' '

        Write-Error "Error in Get-PopuliToken. $errDetail"

        return $null
    }


}