Revo.MSPartner.psm1

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
function New-RevoPartnerAccess{
    param(
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [string]$TenantID,
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [string]$ClientID,
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [string]$CertificateLocation,
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [securestring]$CertificatePassword,
        [parameter(Mandatory=$false, ParameterSetName = "ServicePrincipal")]
        [switch]$SecureOutput,
        [parameter(Mandatory=$false, ParameterSetName = "ServicePrincipal")]
        [switch]$ForceRefresh,
        [parameter(Mandatory=$false, ParameterSetName = "ServicePrincipal")]
        [switch]$ClearToken
    )
    begin{
        $ErrorActionPreference = "SilentlyContinue"

    }
    process{

        $Module = Get-Module -Name MSAL.PS -ListAvailable
        if($null -eq $Module){
            Install-Module -Name MSAL.PS -Scope CurrentUser -Force -Confirm:$false;
            Import-Module -Name MSAL.PS -Scope CurrentUser
        }
        else{
            Import-Module -Name MSAL.PS -Scope CurrentUser
        }
        
        if($ClearToken){
            Remove-Variable -Name RevoPartnerBearerToken -Force -ErrorAction SilentlyContinue
            Remove-Variable -Name RevoPartnerBearerTokenDetails -Force -ErrorAction SilentlyContinue
            Clear-MsalTokenCache -ErrorAction SilentlyContinue
        }

        $CerLocValidation = Test-Path -Path $CertificateLocation -ErrorAction SilentlyContinue

        if(!$CerLocValidation){
            $CertLocationInvalid = $true
        }
        else {
            $ErrorActionPreference = 'SilentlyContinue'
            $Flag = [System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable 
            $Certificate = [System.Security.Cryptography.X509Certificates.X509Certificate2]::new($CertificateLocation,$CertificatePassword,$Flag)
            if($Certificate){
                $BearerValue = Get-Variable -Name "RevoPartnerBearerToken" -ValueOnly -ErrorAction SilentlyContinue
                if($ForceRefresh -and $BearerValue){
                    $ParseInformation = Get-MsalToken -ClientId $ClientID -TenantId $TenantID -ClientCertificate $Certificate -Scopes 'https://graph.windows.net/.default' -ForceRefresh
                }
                else{
                    $ParseInformation = Get-MsalToken -ClientId $ClientID -TenantId $TenantID -ClientCertificate $Certificate -Scopes 'https://graph.windows.net/.default'
                }
            }
            else {
                $CertPasswordInvalid = $true
            }

        }
        
    }
    end{
        $ErrorActionPreference = "Continue"
        if($CertLocationInvalid){
            Write-Error "Can't find the certificate. Please check your path."
        }
        elseif ($CertPasswordInvalid) {
            Write-Error "Certificate password incorrect. Please check the value."
        }
        else{
            New-Variable -Name "RevoPartnerBearerToken" -Value ($ParseInformation.TokenType + " " + $ParseInformation.AccessToken) -Scope Global -Force -ErrorAction SilentlyContinue
            New-Variable -Name "RevoPartnerBearerTokenDetails" -Value $ParseInformation -Scope Global -Force -ErrorAction SilentlyContinue
            if(!$SecureOutput){
                Return $ParseInformation.TokenType + " " + $ParseInformation.AccessToken
            }
        }
    }
}

function New-RevoPartnerAccessByToken{
    param(
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [string]$ClientID,
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [string]$ResponseToken,
        [parameter(Mandatory=$true, ParameterSetName = "ServicePrincipal")]
        [string]$RefreshToken,
        [parameter(Mandatory=$false, ParameterSetName = "ServicePrincipal")]
        [switch]$SecureOutput
    )
    begin{
        $ErrorActionPreference = "SilentlyContinue"

    }
    process{

        $Internal_AuthHost = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
        $Internal_ContentType = 'application/x-www-form-urlencoded'
        $Internal_Body = "client_id=$ENV:HS_AppId&scope=https://api.partnercenter.microsoft.com/user_impersonation%20offline_access&code=$ENV:HS_ResponseToken&grant_type=refresh_token&refresh_token=$ENV:HS_RefreshToken"
        $Internal_AccessToken = Invoke-WebRequest -Uri $Internal_AuthHost -ContentType $Internal_ContentType -Method POST -Body $Internal_Body
        $ParseInformation = ($Internal_AccessToken.Content | ConvertFrom-Json) 
        
    }
    end{
        $ErrorActionPreference = "Continue"
        New-Variable -Name "RevoPartnerBearerToken" -Value ($ParseInformation.token_type + " " + $ParseInformation.access_token) -Scope Global -Force -ErrorAction SilentlyContinue
        New-Variable -Name "RevoPartnerBearerTokenDetails" -Value $ParseInformation -Scope Global -Force -ErrorAction SilentlyContinue
        if(!$SecureOutput){
            Return $ParseInformation.TokenType + " " + $ParseInformation.AccessToken
        }
    }
}

function Get-RevoPartnerResources{
    param(
        [parameter(Mandatory=$true, ParameterSetName = "Predefined")]
        [ValidateSet("Customers","PartnerProfile", "Subscriptions", IgnoreCase = $true)]
        [string]$Resource,
        [parameter(Mandatory=$true, ParameterSetName = "Custom")]
        [string]$CustomURL,
        [parameter(ParameterSetName = "Predefined")]
        [ValidateScript({$Resource -eq 'Subscriptions'},ErrorMessage = "CustomerID parameters it's only available on Subscriptions resource.")]
        [ValidatePattern('^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$',ErrorMessage = "CustomerID must be the GUID of the Customer Tenant ID.")]
        [string]$CustomerID
        
    )
    begin{
        $ErrorActionPreference = "Stop"
        if($Resource -eq 'Subscriptions' -and !$CustomerID){
            Write-Error "Customer Tenant Id must be send by parameter CustomerID. Please validate and try again."
            break
        }
        $ErrorActionPreference = "SilentlyContinue"
    }
    process{
        $BaseURL = "https://api.partnercenter.microsoft.com/v1"

        if($CustomURL){
            $ResourceURL = $CustomURL
        }
        else {
            switch ($Resource) {
                Customers { $ResourceURL = "/customers" }
                PartnerProfile { $ResourceURL = "/profiles/mpn" }
                Subscriptions { $ResourceURL = "/customers/$CustomerID/subscriptions" }
                Default { $ResourceURL = "/profiles/mpn" }
            }
        }

        $FinalURL = ($BaseURL + $ResourceURL)

        $AccessToken = Get-Variable -Name "RevoPartnerBearerToken" -ValueOnly -ErrorAction SilentlyContinue
        if($null -ne $AccessToken){
            $Headers = @{}
            $Headers.Add("Authorization",$AccessToken)
            $Headers.Add("Accept","application/json")
            $Headers.Add("X-Locale","es-PE")
    
            $WebRequest = Invoke-WebRequest -Method Get -Uri $FinalURL -Headers $Headers -ErrorVariable InvokeError

            if ($InvokeError.Count -gt 0) {
                if($InvokeError.ErrorRecord.ToString() -like "This resource can't be accessed by application credentials."){
                    $ModuleError = "This resource can't be accessed by application credentials. Try something diferent or use another credentials."
                }
                elseif ($InvokeError.ErrorRecord.ErrorDetails) {
                    switch(($InvokeError.ErrorRecord.ErrorDetails.Message | ConvertFrom-Json -Depth 10).code){
                        20002 { $ModuleError = ($InvokeError.ErrorRecord.ErrorDetails.Message | ConvertFrom-Json -Depth 10).description }
                        403 { $ModuleError = ($InvokeError.ErrorRecord.ErrorDetails.Message | ConvertFrom-Json -Depth 10).description }
                        default { $ModuleError = "Cannot access to the resource. Please try with other resource." }
                    }
                }
                else{
                    switch(($InvokeError.ErrorRecord.ErrorDetails.Message | ConvertFrom-Json -Depth 10).error.code){
                        'ExpiredAuthenticationToken' {
                            $ModuleError = "Your bearer token was expired, please reconnect with New-RevoPartnerAccess"
                        }
                        'AuthenticationFailedInvalidHeader'{
                            $ModuleError = "Your bearer token was malformed, please reconnect with New-RevoPartnerAccess"
                        }
                        'AuthenticationFailed'{
                            $ModuleError = "Your bearer token was invalid, please reconnect with New-RevoPartnerAccess"
                        }
                        default {
                            $ModuleError = "Cannot get the bearer token, please first connect by New-RevoPartnerAccess"
                        }
                    }
                }

            }
            else {
                if($WebRequest){
                    if ($WebRequest.Content[0] -ne '{') {
                        $Output = $WebRequest.Content.Substring(1) | ConvertFrom-Json -Depth 10
                    }
                    else {
                        $Output = $WebRequest.Content | ConvertFrom-Json -Depth 10
                    }
                }
                
            }
        }
        else {
            $ModuleError = "Cannot get the bearer token, please first connect by New-RevoPartnerAccess"
        }
    }
    end{
        $ErrorActionPreference = "Continue"
        if($ModuleError){
            Write-Error $ModuleError
        }
        else{
            Return $Output
        }
    }
}