Public/Invoke-SfAuthenticate.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<#
    .SYNOPSIS
    Authenticate to Salesforce using the current org configuration

    .DESCRIPTION
    Authenticate to salesforce using the current org configuration

    .INPUTS
    None. You cannot pipe objects to Invoke-SfAuthenticate.

    .OUTPUTS
    Returns as PSCustomObject with the following members:
        access_token
        id
        instance_url
        issued_at
        signature
        token_type

    .EXAMPLE
    PS> $sfAcessToken = (Invoke-SfAuthenticate).access_token

    .LINK
    Set-Config

    .NOTES
    Assumes config is initialized for org access.
#>

function Invoke-SfAuthenticate {

    [CmdletBinding()]
    [OutputType([PSCustomObject])]
    param()

    begin {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Function started"
    }

    end {
        Write-Verbose "[$($MyInvocation.MyCommand.Name)] Complete"
    }

    process {
        Write-Debug "[$($MyInvocation.MyCommand.Name)] PSBoundParameters: $($PSBoundParameters | Out-String)"

        $config = Get-Config
        $body = @{
            grant_type    = "password"
            client_id     = $config.SfOauth.GetNetworkCredential().username
            client_secret = $config.SfOauth.GetNetworkCredential().password
            username      = $config.SfCredentials.GetNetworkCredential().username
            password      = $config.SfCredentials.GetNetworkCredential().password + $config.SfSecurityToken
        }
        $loginUrl = "https://$(&{If($config.Sandbox){"test"} Else {"login"}}).salesforce.com/services/oauth2/token"
        Write-Debug ($Body | ConvertTo-Json)
        Invoke-RestMethod -Uri $loginUrl -Method POST -Body $body -TimeoutSec 30
    }
}