Microsoft.PowerApps.AuthModule.psm1

$local:ErrorActionPreference = "Stop"

Add-Type -Path (Join-Path (Split-Path $script:MyInvocation.MyCommand.Path) "Microsoft.Identity.Client.dll")

function Get-JwtTokenClaims
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        [string]$JwtToken
    )

    $tokenSplit = $JwtToken.Split(".")
    $claimsSegment = $tokenSplit[1].Replace(" ", "+").Replace("-", "+").Replace('_', '/');
    
    $mod = $claimsSegment.Length % 4
    if ($mod -gt 0)
    {
        $paddingCount = 4 - $mod;
        for ($i = 0; $i -lt $paddingCount; $i++)
        {
            $claimsSegment += "="
        }
    }

    $decodedClaimsSegment = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($claimsSegment))

    return ConvertFrom-Json $decodedClaimsSegment
}


function Get-DefaultAudienceForEndPoint
{
    [CmdletBinding()]
    Param(
        [string] $Endpoint
    )

    $audienceMapping = @{
        "prod" = "https://service.powerapps.com/";
        "preview" = "https://service.powerapps.com/";
        "tip1"= "https://service.powerapps.com/";
        "tip2"= "https://service.powerapps.com/";
        "usgov"= "https://gov.service.powerapps.us/";
        "usgovhigh"= "https://high.service.powerapps.us/";
        "dod" = "https://service.apps.appsplatform.us/";
        "china" = "https://service.powerapps.cn/";
    }

    if ($null -ne $audienceMapping[$Endpoint])
    {
        return $audienceMapping[$Endpoint];
    }

    Write-Verbose "Unknown endpoint $Endpoint. Using https://service.powerapps.com/ as a default";
    return "https://service.powerapps.com/";
}

function RemoveHttpHttps {
    param (
        [string] $inputString
    )

    foreach($removalTarget in @('http://','https://'))
    {
        if($inputString.StartsWith($removalTarget))
        {
            $inputString = $inputString.Remove(0, $removalTarget.Length)
        }
    }

    return $inputString
}

function Await-Task {
    param (
        [Parameter(ValueFromPipeline=$true, Mandatory=$true)]
        $task
    )

    process {
        while (-not $task.AsyncWaitHandle.WaitOne(200)) { }
        $task.GetAwaiter().GetResult()
    }
}

function Add-PowerAppsAccount
{
    <#
    .SYNOPSIS
    Add PowerApps account.
    .DESCRIPTION
    The Add-PowerAppsAccount cmdlet logins the user or application account and save login information to cache.
    Use 'Get-Help Add-PowerAppsAccount -Detailed' for descriptions of the parameters and example usages.
    .PARAMETER Audience
    The service audience which is used for login.
    .PARAMETER Endpoint
    The serivce endpoint which to call. The value can be "prod", "preview", "tip1", "tip2", "usgov", "dod", "usgovhigh", or "china".
    Can't be used if providing endpoint overrides
    .PARAMETER Username
    The user name used for login.
    .PARAMETER Password
    The password for the user.
    .PARAMETER TenantID
    The tenant Id of the user or application.
    .PARAMETER CertificateThumbprint
    The certificate thumbprint of the application.
    .PARAMETER ClientSecret
    The client secret of the application.
    .PARAMETER ApplicationId
    The application Id.
    .PARAMETER AudienceOverride
    Must be provided if giving endpoint overrides; this audience will be used for all subsequent auth calls, ignoring normally derived audiences
    .PARAMETER AuthBaseUriOverride
    Must be provided if giving endpoint overrides
    .PARAMETER FlowEndpointOverride
    Must be provided if giving endpoint overrides
    .PARAMETER PowerAppsEndpointOverride
    Must be provided if giving endpoint overrides
    .PARAMETER BapEndpointOverride
    Must be provided if giving endpoint overrides
    .PARAMETER GraphEndpointOverride
    Must be provided if giving endpoint overrides
    .PARAMETER CdsOneEndpointOverride
    Can be provided if giving endpoint overrides
    .PARAMETER PvaEndpointOverride
    Can be provided if giving endpoint overrides
    .EXAMPLE
    Add-PowerAppsAccount
    Login to "prod" endpoint.
    .EXAMPLE
    Add-PowerAppsAccount -Endpoint "prod" -Username "username@test.onmicrosoft.com" -Password "password"
    Login to "prod" for user "username@test.onmicrosoft.com" by using password "password"
    .EXAMPLE
    Add-PowerAppsAccount `
      -Endpoint "tip1" `
      -TenantID 1a1fbe33-1ff4-45b2-90e8-4628a5112345 `
      -ClientSecret ABCDE]NO_8:YDLp0J4o-:?=K9cmipuF@ `
      -ApplicationId abcdebd6-e62c-4f68-ab74-b046579473ad
    Login to "tip1" for application abcdebd6-e62c-4f68-ab74-b046579473ad in tenant 1a1fbe33-1ff4-45b2-90e8-4628a5112345 by using client secret.
    .EXAMPLE
    Add-PowerAppsAccount `
      -Endpoint "tip1" `
      -TenantID 1a1fbe33-1ff4-45b2-90e8-4628a5112345 `
      -CertificateThumbprint 12345137C1B2D4FED804DB353D9A8A18465C8027 `
      -ApplicationId 08627eb8-8eba-4a9a-8c49-548266012345
    Login to "tip1" for application 08627eb8-8eba-4a9a-8c49-548266012345 in tenant 1a1fbe33-1ff4-45b2-90e8-4628a5112345 by using certificate.
    .EXAMPLE
    Add-PowerAppsAccount `
      -AudienceOverride: "https://service.powerapps.com/" `
      -AuthBaseUriOverride: "https://login.microsoftonline.com" `
      -BapEndpointOverride: "api.bap.microsoft.com" `
      -CdsOneEndpointOverride: "api.cds.microsoft.com" `
      -FlowEndpointOverride: "api.flow.microsoft.com" `
      -GraphEndpointOverride: "graph.windows.net" `
      -PowerAppsEndpointOverride: "api.powerapps.com" `
      -PvaEndpointOverride: "powerva.microsoft.com"
    Login to an environment with the provided endpoints (examples above are for 'PROD')
    .EXAMPLE
    $Inputs | Add-PowerAppsAccount
    Login to an environment with the endpionts stored in a PS Custom Object variable; where its content is defined as:
    $Inputs = [pscustomobject]@{ `
      "AudienceOverride" = "https://service.powerapps.com/"; `
      "AuthBaseUriOverride" = "https://login.microsoftonline.com"; `
      "BapEndpointOverride" = "api.bap.microsoft.com"; `
      "CdsOneEndpointOverride" = "api.cds.microsoft.com"; `
      "FlowEndpointOverride" = "api.flow.microsoft.com"; `
      "GraphEndpointOverride" = "graph.windows.net"; `
      "PowerAppsEndpointOverride" = "api.powerapps.com"; `
      "PvaEndpointOverride" = "powerva.microsoft.com" }
    .EXAMPLE
    Get-Content -Raw ".\OverrideEndpoints.json" | ConvertFrom-Json | Add-PowerAppsAccount
    Login to an environment with the endpoints stored in 'OverrideEndpoints.json'; where its content is of the form:
    {
      "AudienceOverride": "https://service.powerapps.com/",
      "AuthBaseUriOverride": "https://login.microsoftonline.com",
      "BapEndpointOverride": "api.bap.microsoft.com",
      "CdsOneEndpointOverride": "api.cds.microsoft.com",
      "FlowEndpointOverride": "api.flow.microsoft.com",
      "GraphEndpointOverride": "graph.windows.net",
      "PowerAppsEndpointOverride": "api.powerapps.com",
      "PvaEndpointOverride": "powerva.microsoft.com"
    }
    #>

    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $false, ParameterSetName="DerivedEndpoints")]
        [string] $Audience = "https://service.powerapps.com/",

        [Parameter(Mandatory = $false, ParameterSetName="DerivedEndpoints")]
        [ValidateSet("prod","preview","tip1", "tip2", "usgov", "usgovhigh", "dod", "china")]
        [string]$Endpoint = "prod",

        [string]$Username = $null,

        [SecureString]$Password = $null,

        [string]$TenantID = $null,

        [string]$CertificateThumbprint = $null,

        [string]$ClientSecret = $null,

        [string]$ApplicationId = "1950a258-227b-4e31-a9cf-717495945fc2",

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $AudienceOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $AuthBaseUriOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $FlowEndpointOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $PowerAppsEndpointOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $BapEndpointOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $GraphEndpointOverride,

        [Parameter(Mandatory = $false,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $CdsOneEndpointOverride = "unsupported",

        [Parameter(Mandatory = $false,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $PvaEndpointOverride = "unsupported"
    )

    if ($Audience -eq "https://service.powerapps.com/" -and -not $PSBoundParameters.ContainsKey('AudienceOverride'))
    {
        # It's the default audience - we should remap based on endpoint as needed
        $Audience = Get-DefaultAudienceForEndPoint($Endpoint)
        $PSBoundParameters['Audience'] = $Audience
    }

    $global:currentSession = $null
    Add-PowerAppsAccountInternal @PSBoundParameters
}

function Add-PowerAppsAccountInternal
{
    param
    (
        [Parameter(Mandatory = $false, ParameterSetName="DerivedEndpoints")]
        [string] $Audience = "https://service.powerapps.com/",

        [Parameter(Mandatory = $false, ParameterSetName="DerivedEndpoints")]
        [ValidateSet("prod","preview","tip1", "tip2", "usgov", "usgovhigh", "dod", "china")]
        [string]$Endpoint = "prod",

        [string]$Username = $null,

        [SecureString]$Password = $null,

        [string]$TenantID = $null,

        [string]$CertificateThumbprint = $null,

        [string]$ClientSecret = $null,

        [string]$ApplicationId = "1950a258-227b-4e31-a9cf-717495945fc2",

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $AudienceOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $AuthBaseUriOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $FlowEndpointOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $PowerAppsEndpointOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $BapEndpointOverride,

        [Parameter(Mandatory = $true,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $GraphEndpointOverride,

        [Parameter(Mandatory = $false,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $CdsOneEndpointOverride = "unsupported",

        [Parameter(Mandatory = $false,ParameterSetName="ProvidedEndpoints", ValueFromPipelineByPropertyName)]
        [string] $PvaEndpointOverride = "unsupported"
    )

    $InputEndpoint = $Endpoint

    #Enforce format requirements for endpoint overrides and force their usage
    if ($PSBoundParameters.ContainsKey('AudienceOverride') -and $PSBoundParameters.ContainsKey('AuthBaseUriOverride') -and $PSBoundParameters.ContainsKey('FlowEndpointOverride') -and $PSBoundParameters.ContainsKey('PowerAppsEndpointOverride') -and $PSBoundParameters.ContainsKey('BapEndpointOverride') -and $PSBoundParameters.ContainsKey('GraphEndpointOverride'))
    {
        $InputEndpoint = 'override'

        Write-Verbose "Overrides were passed and will be used in place of any derived audiences or endpoints; run this command again to change configured overrides"
        #Ensure exactly 1 trailing '/'
        $AudienceOverride = $AudienceOverride.TrimEnd('/') + '/';
        $Audience = $AudienceOverride

        #Ensure no trailing '/'
        $AuthBaseUriOverride = $AuthBaseUriOverride.TrimEnd('/');

        #Ensure no leading 'http://' or 'https://' and no trailing '/'
        $FlowEndpointOverride = RemoveHttpHttps $FlowEndpointOverride.TrimEnd('/')
        $PowerAppsEndpointOverride = RemoveHttpHttps $PowerAppsEndpointOverride.TrimEnd('/')
        $BapEndpointOverride = RemoveHttpHttps $BapEndpointOverride.TrimEnd('/')
        $GraphEndpointOverride = RemoveHttpHttps $GraphEndpointOverride.TrimEnd('/')
        $CdsOneEndpointOverride = RemoveHttpHttps $CdsOneEndpointOverride.TrimEnd('/')
        $PvaEndpointOverride = RemoveHttpHttps $PvaEndpointOverride.TrimEnd('/')
    }
    elseif ($global:currentSession.audienceOverride -ne $null -and $global:currentSession.audienceOverride -ne '')
    {
        Write-Debug "Provided Audience '$Audience' is being replaced with previously provided override value '$($global:currentSession.audienceOverride)'"
        $Audience = $global:currentSession.audienceOverride
    }

    [string[]]$scopes = "$Audience/.default"
    if ([string]::IsNullOrWhiteSpace($ApplicationId))
    {
        $ApplicationId = "1950a258-227b-4e31-a9cf-717495945fc2"
    }

    Write-Debug "Using appId, $ApplicationId"

    [Microsoft.Identity.Client.IClientApplicationBase]$clientBase = $null
    [Microsoft.Identity.Client.AuthenticationResult]$authResult = $null

    if ($global:currentSession.loggedIn -eq $true -and $global:currentSession.recursed -ne $true)
    {
        Write-Debug "Already logged in, checking for token for resource $Audience"
        $authResult = $null
        
        if ($global:currentSession.resourceTokens[$Audience] -ne $null)
        {
            if ($global:currentSession.resourceTokens[$Audience].accessToken -ne $null -and `
                $global:currentSession.resourceTokens[$Audience].expiresOn -ne $null -and `
                $global:currentSession.resourceTokens[$Audience].expiresOn -gt (Get-Date))
            {
                Write-Debug "Token found and value, returning for audience $Audience"
                return
            }
            else
            {
                 # Already logged in with an account, silently asking for a token from MSAL which should refresh
                try
                {
                    Write-Debug "Already logged in, silently requesting token from MSAL"
                    $authResult = $global:currentSession.msalClientApp.AcquireTokenSilent($scopes, $global:currentSession.msalAccount).ExecuteAsync() | Await-Task
                }
                catch [Microsoft.Identity.Client.MsalUiRequiredException] 
                {
                    Write-Debug ('{0}: {1}' -f $_.Exception.GetType().Name, $_.Exception.Message)
                }
            }
        }

        if ($authResult -eq $null)
        {
            Write-Debug "No token found, reseting audience and recursing: $Audience"
            # Reset the current audience values and call Add-PowerAppsAccount again
            $global:currentSession.resourceTokens[$Audience] = $null
            $global:currentSession.recursed = $true

            $PSBoundParameters['Audience'] = $Audience

            # the override endpoint is set automatically when required params are passed
            if ($global:currentSession.endpoint -ne 'override')
            {
                $PSBoundParameters['Endpoint'] = $global:currentSession.endpoint
            }

            $PSBoundParameters['Username'] = $global:currentSession.username
            $PSBoundParameters['Password'] = $global:currentSession.password
            $PSBoundParameters['TenantID'] = $global:currentSession.InitialTenantId
            $PSBoundParameters['CertificateThumbprint'] = $global:currentSession.certificateThumbprint
            $PSBoundParameters['ClientSecret'] = $global:currentSession.clientSecret
            $PSBoundParameters['ApplicationId'] = $global:currentSession.applicationId

            Add-PowerAppsAccountInternal @PSBoundParameters
            $global:currentSession.recursed = $false

            # Afer recursing we can early return
            return
        }
    }
    else
    {
        [string] $jwtTokenForClaims = $null

        if ($InputEndpoint -ne "override")
        {
            [Microsoft.Identity.Client.AzureCloudInstance] $authBaseUri =
                switch ($InputEndpoint)
                    {
                        "usgov"     { [Microsoft.Identity.Client.AzureCloudInstance]::AzurePublic }
                        "usgovhigh" { [Microsoft.Identity.Client.AzureCloudInstance]::AzureUsGovernment }
                        "dod"       { [Microsoft.Identity.Client.AzureCloudInstance]::AzureUsGovernment }
                        "china"     { [Microsoft.Identity.Client.AzureCloudInstance]::AzureChina }
                        default     { [Microsoft.Identity.Client.AzureCloudInstance]::AzurePublic }
                    };
        }
        else
        {
            [string] $authBaseUri = $AuthBaseUriOverride
        }

        if ($Username -ne $null -and $Password -ne $null)
        {
            $authUriWithAudience = $AuthBaseUriOverride + "/organizations/"
            [Microsoft.Identity.Client.AadAuthorityAudience] $aadAuthAudience = [Microsoft.Identity.Client.AadAuthorityAudience]::AzureAdMultipleOrgs
        }
        else
        {
            $authUriWithAudience = $AuthBaseUriOverride + "/common/"
            [Microsoft.Identity.Client.AadAuthorityAudience] $aadAuthAudience = [Microsoft.Identity.Client.AadAuthorityAudience]::AzureAdAndPersonalMicrosoftAccount
        }

        Write-Debug "Using $Audience : $ApplicationId : $aadAuthAudience : $authUriWithAudience"

        if (![string]::IsNullOrWhiteSpace($TenantID) -and `
            (![string]::IsNullOrWhiteSpace($ClientSecret) -or ![string]::IsNullOrWhiteSpace($CertificateThumbprint)))
        {
            $options = New-Object -TypeName Microsoft.Identity.Client.ConfidentialClientApplicationOptions
            $options.ClientId = $ApplicationId
            $options.TenantId = $TenantID

            [Microsoft.Identity.Client.IConfidentialClientApplication ]$ConfidentialClientApplication = $null

            if (![string]::IsNullOrWhiteSpace($CertificateThumbprint))
            {
                Write-Debug "Using certificate for token acquisition"
                $clientCertificate = [Array] (Get-ChildItem -path Cert:*$CertificateThumbprint -Recurse)
                if ($clientCertificate.Length -gt 1)
                {
                    Write-Debug "Multiple instances of the certificate found"
                    $matchingCertificate = $null
                    foreach ($certificateInstance in $clientCertificate)
                    {
                        if ($null -ne $certificateInstance.PrivateKey)
                        {
                            Write-Debug "Found certificate instance with associated private key"
                            $matchingCertificate = $certificateInstance
                            break
                        }
                    }
                    if ($null -eq $matchingCertificate)
                    {
                        throw "Could not find an instance of a certificate with associated private key for thumbprint $CertificateThumbprint"
                    }
                    $clientCertificate = $matchingCertificate
                }
                elseif ($clientCertificate.Length -eq 1)
                {
                    Write-Debug "A single instance of the certificate was found"
                    $clientCertificate = $clientCertificate[0]
                }
                else
                {
                    throw "Could not find an instance of a certificate with thumbprint $CertificateThumbprint"
                }
                $ConfidentialClientApplication = [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($ApplicationId).WithCertificate($clientCertificate).WithAuthority($authBaseUri, $TenantID, $true).Build()
            }
            else
            {
                Write-Debug "Using clientSecret for token acquisition"
                $ConfidentialClientApplication = [Microsoft.Identity.Client.ConfidentialClientApplicationBuilder]::Create($ApplicationId).WithClientSecret($ClientSecret).WithAuthority($authBaseUri, $TenantID, $true).Build()
            }

            $authResult = $ConfidentialClientApplication.AcquireTokenForClient($scopes).ExecuteAsync() | Await-Task
            $clientBase = $ConfidentialClientApplication
        }
        else
        {
            if ($InputEndpoint -eq "override")
            {
                $PublicClientApplication = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($ApplicationId).WithAuthority($authUriWithAudience, $true).WithDefaultRedirectUri().Build()
            }
            else
            {
                $PublicClientApplication = [Microsoft.Identity.Client.PublicClientApplicationBuilder]::Create($ApplicationId).WithAuthority($authBaseUri, $aadAuthAudience, $true).WithDefaultRedirectUri().Build()
            }

            if ($Username -ne $null -and $Password -ne $null)
            {
                Write-Debug "Using username, password"
                $authResult = $PublicClientApplication.AcquireTokenByUsernamePassword($scopes, $UserName, $Password).ExecuteAsync() | Await-Task
            }
            else
            {
                Write-Debug "Using interactive login"
                $authResult = $PublicClientApplication.AcquireTokenInteractive($scopes).ExecuteAsync() | Await-Task
            }

            $clientBase = $PublicClientApplication
        }
    }

    if ($authResult -ne $null)
    {
        if (![string]::IsNullOrWhiteSpace($authResult.IdToken))
        {
            $jwtTokenForClaims = $authResult.IdToken
        }
        else
        {
            $jwtTokenForClaims = $authResult.AccessToken
        }

        $claims = Get-JwtTokenClaims -JwtToken $jwtTokenForClaims

        if ($global:currentSession.loggedIn -eq $true)
        {
           Write-Debug "Adding new audience '$Audience' to resourceToken map. Expires $($authResult.ExpiresOn)"
            # addition of a new token for a new audience
            $global:currentSession.resourceTokens[$Audience] = @{
                accessToken = $authResult.AccessToken;
                expiresOn = $authResult.ExpiresOn;
            };

            if ($AudienceOverride -ne $null -and $AudienceOverride -ne '')
            {
                Write-Debug "A new audience override '$AudienceOverride' was provided and is in use, instead of the previous audience override '$($global:currentSession.audienceOverride)', for all token aquisitions"
                $global:currentSession.audienceOverride = $AudienceOverride
            }
        }
        else
        {
            Write-Debug "Adding first audience '$Audience' to resourceToken map. Expires $($authResult.ExpiresOn)"
            $global:currentSession = @{
                audienceOverride = $AudienceOverride;
                loggedIn = $true;
                recursed = $false;
                endpoint = $InputEndpoint;
                msalClientApp = $clientBase;
                msalAccount = $authResult.Account;
                upn = $claims.upn;
                InitialTenantId = $TenantID;
                tenantId = $claims.tid;
                userId = $claims.oid;
                applicationId = $ApplicationId;
                username = $Username;
                password = $Password;
                certificateThumbprint = $CertificateThumbprint;
                clientSecret = $ClientSecret;
                resourceTokens = @{
                    $Audience = @{
                        accessToken = $authResult.AccessToken;
                        expiresOn = $authResult.ExpiresOn;
                    }
                };
                selectedEnvironment = "~default";
                flowEndpoint = 
                    switch ($InputEndpoint)
                    {
                        "override"  { $FlowEndpointOverride }
                        "prod"      { "api.flow.microsoft.com" }
                        "usgov"     { "gov.api.flow.microsoft.us" }
                        "usgovhigh" { "high.api.flow.microsoft.us" }
                        "dod"       { "api.flow.appsplatform.us" }
                        "china"     { "api.powerautomate.cn" }
                        "preview"   { "preview.api.flow.microsoft.com" }
                        "tip1"      { "tip1.api.flow.microsoft.com"}
                        "tip2"      { "tip2.api.flow.microsoft.com" }
                        default     { throw "Unsupported endpoint '$InputEndpoint'"}
                    };
                powerAppsEndpoint = 
                    switch ($InputEndpoint)
                    {
                        "override"  { $PowerAppsEndpointOverride }
                        "prod"      { "api.powerapps.com" }
                        "usgov"     { "gov.api.powerapps.us" }
                        "usgovhigh" { "high.api.powerapps.us" }
                        "dod"       { "api.apps.appsplatform.us" }
                        "china"     { "api.powerapps.cn" }
                        "preview"   { "preview.api.powerapps.com" }
                        "tip1"      { "tip1.api.powerapps.com"}
                        "tip2"      { "tip2.api.powerapps.com" }
                        default     { throw "Unsupported endpoint '$InputEndpoint'"}
                    };            
                bapEndpoint = 
                    switch ($InputEndpoint)
                    {
                        "override"  { $BapEndpointOverride }
                        "prod"      { "api.bap.microsoft.com" }
                        "usgov"     { "gov.api.bap.microsoft.us" }
                        "usgovhigh" { "high.api.bap.microsoft.us" }
                        "dod"       { "api.bap.appsplatform.us" }
                        "china"     { "api.bap.partner.microsoftonline.cn" }
                        "preview"   { "preview.api.bap.microsoft.com" }
                        "tip1"      { "tip1.api.bap.microsoft.com"}
                        "tip2"      { "tip2.api.bap.microsoft.com" }
                        default     { throw "Unsupported endpoint '$InputEndpoint'"}
                    };      
                graphEndpoint = 
                    switch ($InputEndpoint)
                    {
                        "override"  { $GraphEndpointOverride }
                        "prod"      { "graph.windows.net" }
                        "usgov"     { "graph.windows.net" }
                        "usgovhigh" { "graph.windows.net" }
                        "dod"       { "graph.windows.net" }
                        "china"     { "graph.windows.net" }
                        "preview"   { "graph.windows.net" }
                        "tip1"      { "graph.windows.net"}
                        "tip2"      { "graph.windows.net" }
                        default     { throw "Unsupported endpoint '$InputEndpoint'"}
                    };
                cdsOneEndpoint = 
                    switch ($InputEndpoint)
                    {
                        "override"  { $CdsOneEndpointOverride }
                        "prod"      { "api.cds.microsoft.com" }
                        "usgov"     { "gov.api.cds.microsoft.us" }
                        "usgovhigh" { "high.api.cds.microsoft.us" }
                        "dod"       { "dod.gov.api.cds.microsoft.us" }
                        "china"     { "unsupported" }
                        "preview"   { "preview.api.cds.microsoft.com" }
                        "tip1"      { "tip1.api.cds.microsoft.com"}
                        "tip2"      { "tip2.api.cds.microsoft.com" }
                        default     { throw "Unsupported endpoint '$InputEndpoint'"}
                    };
                pvaEndpoint = 
                    switch ($InputEndpoint)
                    {
                        "override"  { $PvaEndpointOverride }
                        "prod"      { "powerva.microsoft.com" }
                        "usgov"     { "gcc.api.powerva.microsoft.us" }
                        "usgovhigh" { "high.api.powerva.microsoft.us" }
                        "dod"       { "powerva.api.appsplatform.us" }
                        "china"     { "unsupported" }
                        "preview"   { "bots.sdf.customercareintelligence.net" }
                        "tip1"       { "bots.ppe.customercareintelligence.net"}
                        "tip2"       { "bots.int.customercareintelligence.net"}
                        default     { throw "Unsupported endpoint '$InputEndpoint'"}
                    };
            };
        }
    }
}


function Test-PowerAppsAccount
{
    <#
    .SYNOPSIS
    Test PowerApps account.
    .DESCRIPTION
    The Test-PowerAppsAccount cmdlet checks cache and calls Add-PowerAppsAccount if user account is not in cache.
    Use Get-Help Test-PowerAppsAccount -Examples for more detail.
    .EXAMPLE
    Test-PowerAppsAccount
    Check if user account is cached.
    #>

    [CmdletBinding()]
    param
    (
    )

    if (-not $global:currentSession -or $global:currentSession.loggedIn -ne $true)
    {
        Add-PowerAppsAccountInternal
    }
}

function Remove-PowerAppsAccount
{
    <#
    .SYNOPSIS
    Remove PowerApps account.
    .DESCRIPTION
    The Remove-PowerAppsAccount cmdlet removes the user or application login information from cache.
    Use Get-Help Remove-PowerAppsAccount -Examples for more detail.
    .EXAMPLE
    Remove-PowerAppsAccount
    Removes the login information from cache.
    #>

    [CmdletBinding()]
    param
    (
    )

    if ($global:currentSession -ne $null -and $global:currentSession.upn -ne $null)
    {
        Write-Verbose "Logging out $($global:currentSession.upn)"
    }
    else
    {
        Write-Verbose "No user logged in"
    }

    $global:currentSession = @{
        loggedIn = $false;
    };
}

function Get-JwtToken
{
    <#
    .SYNOPSIS
    Get user login token.
    .DESCRIPTION
    The Get-JwtToken cmdlet get the user or application login information from cache. It will call Add-PowerAppsAccount if login token expired.
    Use Get-Help Get-JwtToken -Examples for more detail.
    .EXAMPLE
    Get-JwtToken "https://service.powerapps.com/"
    Get login token for PowerApps "prod".
    #>

    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        [string] $Audience
    )

    if ($global:currentSession -eq $null)
    {
        $global:currentSession = @{
            loggedIn = $false;
        };
    }
    elseif($global:currentSession.audienceOverride -ne $null -and $global:currentSession.audienceOverride -ne '')
    {
        Write-Verbose "The provided audience '$Audience' will be ignored in place of the AudienceOverride '$($global:currentSession.audienceOverride)' provided in the most recent call to Add-PowerAppsAccount"
        $Audience = $global:currentSession.audienceOverride
    }

    Add-PowerAppsAccountInternal -Audience $Audience

    return $global:currentSession.resourceTokens[$Audience].accessToken;
}

function Invoke-OAuthDialog
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$true)]
        [string] $ConsentLinkUri
    )

    Add-Type -AssemblyName System.Windows.Forms
    $form = New-Object -TypeName System.Windows.Forms.Form -Property @{ Width=440; Height=640 }
    $web  = New-Object -TypeName System.Windows.Forms.WebBrowser -Property @{ Width=420; Height=600; Url=$ConsentLinkUri }
    $DocComp  = {
        $Global:uri = $web.Url.AbsoluteUri        
        if ($Global:uri -match "error=[^&]*|code=[^&]*")
        {
            $form.Close()
        }
    }
    $web.ScriptErrorsSuppressed = $true
    $web.Add_DocumentCompleted($DocComp)
    $form.Controls.Add($web)
    $form.Add_Shown({$form.Activate()})
    $form.ShowDialog() | Out-Null
    $queryOutput = [System.Web.HttpUtility]::ParseQueryString($web.Url.Query)

    $output = @{}

    foreach($key in $queryOutput.Keys)
    {
        $output["$key"] = $queryOutput[$key]
    }
    
    return $output
}


function Get-TenantDetailsFromGraph
{
    <#
    .SYNOPSIS
    Get my organization tenant details from graph.
    .DESCRIPTION
    The Get-TenantDetailsFromGraph function calls graph and gets my organization tenant details.
    Use Get-Help Get-TenantDetailsFromGraph -Examples for more detail.
    .PARAMETER GraphApiVersion
    Graph version to call. The default version is "1.6".
    .EXAMPLE
    Get-TenantDetailsFromGraph
    Get my organization tenant details from graph by calling graph service in version 1.6.
    #>

    param
    (
        [string]$GraphApiVersion = "1.6"
    )

    process 
    {
        $TenantIdentifier = "myorganization"

        $route = "https://{graphEndpoint}/{tenantIdentifier}/tenantDetails`?api-version={graphApiVersion}" `
        | ReplaceMacro -Macro "{tenantIdentifier}" -Value $TenantIdentifier `
        | ReplaceMacro -Macro "{graphApiVersion}" -Value $GraphApiVersion;

        $graphResponse = InvokeApi -Method GET -Route $route
        
        if ($graphResponse.value -ne $null)
        {
            CreateTenantObject -TenantObj $graphResponse.value
        }
        else
        {
            return $graphResponse
        }
    }
}

#Returns users or groups from Graph
#wrapper on top of https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/users-operations & https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/groups-operations
function Get-UsersOrGroupsFromGraph(
)
{
    <#
    .SYNOPSIS
    Returns users or groups from Graph.
    .DESCRIPTION
    The Get-UsersOrGroupsFromGraph function calls graph and gets users or groups from Graph.
    Use Get-Help Get-UsersOrGroupsFromGraph -Examples for more detail.
    .PARAMETER ObjectId
    User objec Id.
    .PARAMETER SearchString
    Search string.
    .PARAMETER GraphApiVersion
    Graph version to call. The default version is "1.6".
    .EXAMPLE
    Get-UsersOrGroupsFromGraph -ObjectId "12345ba9-805f-43f8-98f7-34fa34aa51a7"
    Get user with user object Id "12345ba9-805f-43f8-98f7-34fa34aa51a7" from graph by calling graph service in version 1.6.
    .EXAMPLE
    Get-UsersOrGroupsFromGraph -SearchString "gfd"
    Get users who's UserPrincipalName starting with "gfd" from graph by calling graph service in version 1.6.
    #>

    [CmdletBinding(DefaultParameterSetName="Id")]
    param
    (
        [Parameter(Mandatory = $true, ParameterSetName = "Id")]
        [string]$ObjectId,

        [Parameter(Mandatory = $true, ParameterSetName = "Search")]
        [string]$SearchString,

        [Parameter(Mandatory = $false, ParameterSetName = "Search")]
        [Parameter(Mandatory = $false, ParameterSetName = "Id")]
        [string]$GraphApiVersion = "1.6"
    )

    Process
    {
        if (-not [string]::IsNullOrWhiteSpace($ObjectId))
        {
            $userGraphUri = "https://graph.windows.net/myorganization/users/{userId}`?&api-version={graphApiVersion}" `
            | ReplaceMacro -Macro "{userId}" -Value $ObjectId `
            | ReplaceMacro -Macro "{graphApiVersion}" -Value $GraphApiVersion;

            $userGraphResponse = InvokeApi -Route $userGraphUri -Method GET
            
            If($userGraphResponse.StatusCode -eq $null)
            {
                CreateUserObject -UserObj $userGraphResponse
            }

            $groupsGraphUri = "https://graph.windows.net/myorganization/groups/{groupId}`?api-version={graphApiVersion}" `
            | ReplaceMacro -Macro "{groupId}" -Value $ObjectId `
            | ReplaceMacro -Macro "{graphApiVersion}" -Value $GraphApiVersion;

            $groupGraphResponse = InvokeApi -Route $groupsGraphUri -Method GET

            If($groupGraphResponse.StatusCode -eq $null)
            {
                CreateGroupObject -GroupObj $groupGraphResponse
            }
        }
        else 
        {
            $userFilter = "startswith(userPrincipalName,'$SearchString') or startswith(displayName,'$SearchString')"
    
            $userGraphUri = "https://graph.windows.net/myorganization/users`?`$filter={filter}&api-version={graphApiVersion}" `
            | ReplaceMacro -Macro "{filter}" -Value $userFilter `
            | ReplaceMacro -Macro "{graphApiVersion}" -Value $GraphApiVersion;

            $userGraphResponse = InvokeApi -Route $userGraphUri -Method GET
    
            foreach($user in $userGraphResponse.value)
            {
                CreateUserObject -UserObj $user
            }

            $groupFilter = "startswith(displayName,'$SearchString')"
    
            $groupsGraphUri = "https://graph.windows.net/myorganization/groups`?`$filter={filter}&api-version={graphApiVersion}" `
            | ReplaceMacro -Macro "{filter}" -Value $groupFilter `
            | ReplaceMacro -Macro "{graphApiVersion}" -Value $GraphApiVersion;

            $groupsGraphResponse = InvokeApi -Route $groupsGraphUri -Method GET
    
            foreach($group in $groupsGraphResponse.value)
            {
                CreateGroupObject -GroupObj $group
            }    
        }
    }
}


function CreateUserObject
{
    param
    (
        [Parameter(Mandatory = $true)]
        [object]$UserObj
    )

    return New-Object -TypeName PSObject `
        | Add-Member -PassThru -MemberType NoteProperty -Name ObjectType -Value $UserObj.objectType `
        | Add-Member -PassThru -MemberType NoteProperty -Name ObjectId -Value $UserObj.objectId `
        | Add-Member -PassThru -MemberType NoteProperty -Name UserPrincipalName -Value $UserObj.userPrincipalName `
        | Add-Member -PassThru -MemberType NoteProperty -Name Mail -Value $UserObj.mail `
        | Add-Member -PassThru -MemberType NoteProperty -Name DisplayName -Value $UserObj.displayName `
        | Add-Member -PassThru -MemberType NoteProperty -Name AssignedLicenses -Value $UserObj.assignedLicenses `
        | Add-Member -PassThru -MemberType NoteProperty -Name AssignedPlans -Value $UserObj.assignedLicenses `
        | Add-Member -PassThru -MemberType NoteProperty -Name Internal -Value $UserObj;
}

function CreateGroupObject
{
    param
    (
        [Parameter(Mandatory = $true)]
        [object]$GroupObj
    )

    return New-Object -TypeName PSObject `
        | Add-Member -PassThru -MemberType NoteProperty -Name ObjectType -Value $GroupObj.objectType `
        | Add-Member -PassThru -MemberType NoteProperty -Name Objectd -Value $GroupObj.objectId `
        | Add-Member -PassThru -MemberType NoteProperty -Name Mail -Value $GroupObj.mail `
        | Add-Member -PassThru -MemberType NoteProperty -Name DisplayName -Value $GroupObj.displayName `
        | Add-Member -PassThru -MemberType NoteProperty -Name Internal -Value $GroupObj;
}


function CreateTenantObject
{
    param
    (
        [Parameter(Mandatory = $true)]
        [object]$TenantObj
    )

    return New-Object -TypeName PSObject `
        | Add-Member -PassThru -MemberType NoteProperty -Name ObjectType -Value $TenantObj.objectType `
        | Add-Member -PassThru -MemberType NoteProperty -Name TenantId -Value $TenantObj.objectId `
        | Add-Member -PassThru -MemberType NoteProperty -Name Country -Value $TenantObj.countryLetterCode `
        | Add-Member -PassThru -MemberType NoteProperty -Name Language -Value $TenantObj.preferredLanguage `
        | Add-Member -PassThru -MemberType NoteProperty -Name DisplayName -Value $TenantObj.displayName `
        | Add-Member -PassThru -MemberType NoteProperty -Name Domains -Value $TenantObj.verifiedDomains `
        | Add-Member -PassThru -MemberType NoteProperty -Name Internal -Value $TenantObj;
}
# SIG # Begin signature block
# MIIoKwYJKoZIhvcNAQcCoIIoHDCCKBgCAQExDzANBglghkgBZQMEAgEFADB5Bgor
# BgEEAYI3AgEEoGswaTA0BgorBgEEAYI3AgEeMCYCAwEAAAQQH8w7YFlLCE63JNLG
# KX7zUQIBAAIBAAIBAAIBAAIBADAxMA0GCWCGSAFlAwQCAQUABCANTnre35FvduEN
# 2O65rNFXY+dbcv2jpRrbL4hbiGcKnqCCDYUwggYDMIID66ADAgECAhMzAAAEA73V
# lV0POxitAAAAAAQDMA0GCSqGSIb3DQEBCwUAMH4xCzAJBgNVBAYTAlVTMRMwEQYD
# VQQIEwpXYXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYDVQQKExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24xKDAmBgNVBAMTH01pY3Jvc29mdCBDb2RlIFNpZ25p
# bmcgUENBIDIwMTEwHhcNMjQwOTEyMjAxMTEzWhcNMjUwOTExMjAxMTEzWjB0MQsw
# CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVkbW9u
# ZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMR4wHAYDVQQDExVNaWNy
# b3NvZnQgQ29ycG9yYXRpb24wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB
# AQCfdGddwIOnbRYUyg03O3iz19XXZPmuhEmW/5uyEN+8mgxl+HJGeLGBR8YButGV
# LVK38RxcVcPYyFGQXcKcxgih4w4y4zJi3GvawLYHlsNExQwz+v0jgY/aejBS2EJY
# oUhLVE+UzRihV8ooxoftsmKLb2xb7BoFS6UAo3Zz4afnOdqI7FGoi7g4vx/0MIdi
# kwTn5N56TdIv3mwfkZCFmrsKpN0zR8HD8WYsvH3xKkG7u/xdqmhPPqMmnI2jOFw/
# /n2aL8W7i1Pasja8PnRXH/QaVH0M1nanL+LI9TsMb/enW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