-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupdate.ps1
264 lines (233 loc) · 12.7 KB
/
update.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
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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#################################################
# HelloID-Conn-Prov-Target-KPN-Mobile-Services-Update
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
#region functions
function Resolve-KPN-Mobile-ServicesError {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[object]
$ErrorObject
)
process {
$httpErrorObj = [PSCustomObject]@{
ScriptLineNumber = $ErrorObject.InvocationInfo.ScriptLineNumber
Line = $ErrorObject.InvocationInfo.Line
ErrorDetails = $ErrorObject.Exception.Message
FriendlyMessage = $ErrorObject.Exception.Message
}
if (-not [string]::IsNullOrEmpty($ErrorObject.ErrorDetails.Message)) {
$httpErrorObj.ErrorDetails = $ErrorObject.ErrorDetails.Message
} elseif ($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException') {
if ($null -ne $ErrorObject.Exception.Response) {
$streamReaderResponse = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
if (-not [string]::IsNullOrEmpty($streamReaderResponse)) {
$httpErrorObj.ErrorDetails = $streamReaderResponse
}
}
}
try {
$errorDetailsObject = ($httpErrorObj.ErrorDetails | ConvertFrom-Json)
# Make sure to inspect the error result object and add only the error message as a FriendlyMessage.
if ($errorDetailsObject.errors.count -gt 0) {
$httpErrorObj.FriendlyMessage = ($errorDetailsObject.errors -join ', ')
} elseif (-not([string]::IsNullOrEmpty($errorDetailsObject.fault.faultstring))) {
$httpErrorObj.FriendlyMessage = $errorDetailsObject.fault.faultstring
} else {
$httpErrorObj.FriendlyMessage = $errorDetailsObject.message
}
} catch {
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails
}
Write-Output $httpErrorObj
}
}
#endregion
try {
# Verify if [aRef] has a value
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
throw 'The account reference could not be found'
}
$tokenHeaders = [System.Collections.Generic.Dictionary[string, string]]::new()
$tokenHeaders.Add('Content-Type', 'application/x-www-form-urlencoded')
$tokenBody = @{
grant_type = 'client_credentials'
client_id = $actionContext.Configuration.ClientId
client_secret = $actionContext.Configuration.ClientSecret
}
$splatGetToken = @{
Uri = "$($actionContext.Configuration.BaseUrl)/oauth/grip/msm/accesstoken"
Method = 'POST'
Body = $tokenBody
Headers = $tokenHeaders
}
$accessToken = (Invoke-RestMethod @splatGetToken).access_token
Write-Information 'Setting authorization header'
$headers = [System.Collections.Generic.Dictionary[string, string]]::new()
$headers.Add('Authorization', "Bearer $($accessToken)")
Write-Information 'Verifying if a KPN-Mobile-Services account exists'
$splatGetUser = @{
Uri = "$($actionContext.Configuration.BaseUrl)/mobile/kpn/mobileservices/hierarchy/subscribers/$($actionContext.References.Account)"
Method = 'GET'
Headers = $headers
}
$correlatedAccount = (Invoke-RestMethod @splatGetUser)
$outputContext.PreviousData = $correlatedAccount
# Always compare the account against the current account in target system
$actionList = @()
if ($null -ne $correlatedAccount) {
$filteredCorrelatedAccount = $correlatedAccount | Select-Object * -ExcludeProperty path, id, location
$splatCompareProperties = @{
ReferenceObject = @($filteredCorrelatedAccount.PSObject.Properties)
DifferenceObject = @($actionContext.Data.subscriber.PSObject.Properties)
}
$propertiesChangedObject = Compare-Object @splatCompareProperties -PassThru | Where-Object { $_.SideIndicator -eq '=>' }
# Takes the subscriber model and adds all the properties that are populated in the target system and adds them to propertiesChanged.
# This is needed because the API sets properties to its default value when they are not send with the put request.
if ($null -ne $propertiesChangedObject) {
$propertiesChanged = @{}
$actionContext.Data.subscriber.PSObject.Properties | ForEach-Object { $propertiesChanged[$_.Name] = $_.Value }
foreach ($property in $filteredCorrelatedAccount.PSObject.Properties) {
if (-not ($actionContext.Data.subscriber.PSObject.Properties.Name -contains ($property.Name))) {
if (-not([string]::IsNullOrEmpty($property.Value))) {
$propertiesChanged[$property.Name] = $property.Value
}
}
}
}
$splatGetDebtors = @{
Uri = "$($actionContext.Configuration.BaseUrl)/mobile/kpn/mobileservices/hierarchy/children"
Method = 'GET'
Headers = $headers
}
$debtors = (Invoke-RestMethod @splatGetDebtors).result
$costCenters = [System.Collections.Generic.list[object]]::new()
foreach ($debtor in $debtors) {
$splatTotalCostCenters = @{
Uri = "$($actionContext.Configuration.BaseUrl)/mobile/kpn/mobileservices/hierarchy/children?id=$($debtor.id)&from=0&to=1"
Method = 'GET'
Headers = $headers
}
$totalCostCenters = (Invoke-RestMethod @splatTotalCostCenters).total
$splatCostCenters = @{
Uri = "$($actionContext.Configuration.BaseUrl)/mobile/kpn/mobileservices/hierarchy/children?id=$($debtor.id)&from=0&to=$($totalCostCenters)"
Method = 'GET'
Headers = $headers
}
$costCenterResult = ((Invoke-RestMethod @splatCostCenters).result | Where-Object { $_.type -eq 'COST_CENTER' })
foreach ($costCenter in $costCenterResult) {
$costCenterObject = [pscustomobject]@{
id = $costCenter.id
name = $costCenter.name
costcenterNumber = $costCenter.costCenterNumber
}
$costCenters += $costCenterObject
}
}
$actionContext.Data.groupId = ($costCenters | Where-Object { $_.costcenterNumber -eq $actionContext.Data.costCenterNumber }).id
$targetCostCenterId = ($correlatedAccount.path | Where-Object { $_.type -eq 'COST_CENTER' }).id
$outputContext.PreviousData.costCenterNumber = ($costCenters | Where-Object { $_.id -eq $targetCostCenterId }).costcenterNumber
if ($actionContext.Data.groupId -ne $targetCostCenterId) {
$actionList += 'UpdateCostCenter'
}
if ($propertiesChanged) {
$actionList += 'UpdateAccount'
} elseif ($actionContext.Data.groupId -eq $targetCostCenterId) {
$actionList += 'NoChanges'
}
} else {
$actionList += 'NotFound'
}
# Process
foreach ($action in $actionList) {
switch ($action) {
'UpdateAccount' {
Write-Information "Account property(s) required to update: $($propertiesChanged.Name -join ', ')"
$splatUpdateSubscriber = @{
Uri = "$($actionContext.Configuration.BaseUrl)/mobile/kpn/mobileservices/hierarchy/subscribers/$($actionContext.References.Account)"
Method = 'PUT'
Body = ([PSCustomObject]@{
referenceNumber = $actionContext.Data.referenceNumber
subscriber = $propertiesChanged
} | ConvertTo-Json -Depth 10)
Headers = $headers
ContentType = 'application/json'
}
if (-not($actionContext.DryRun -eq $true)) {
Write-Information "Updating KPN-Mobile-Services account with accountReference: [$($actionContext.References.Account)]"
$null = Invoke-RestMethod @splatUpdateSubscriber
} else {
Write-Information "[DryRun] Update KPN-Mobile-Services account with accountReference: [$($actionContext.References.Account)], will be executed during enforcement"
}
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Update account was successful, Account property(s) updated: [$($propertiesChanged.name -join ',')]"
IsError = $false
})
break
}
'UpdateCostCenter' {
Write-Information 'Update subscriber costcenter'
$moveSubscriberBody = @{
destinationGroupId = $actionContext.Data.groupId
}
$splatUpdateSubscriberCostCenter = @{
Uri = "$($actionContext.Configuration.BaseUrl)/mobile/kpn/mobileservices/hierarchy/subscribers/$($actionContext.References.Account)/move"
Method = 'POST'
Body = ($moveSubscriberBody | ConvertTo-Json -Depth 10)
Headers = $headers
ContentType = 'application/json'
}
if (-not($actionContext.DryRun -eq $true)) {
Write-Information "Move account from costcenter [$($targetCostCenterId)] to costcenter [$($actionContext.Data.groupId)]"
$null = Invoke-RestMethod @splatUpdateSubscriberCostCenter
} else {
Write-Information "[DryRun] Move account from costcenter [$($targetCostCenterId)] to costcenter [$($actionContext.Data.groupId)], will be executed during enforcement"
}
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Move account was successful, account moved from costcenter [$($targetCostCenterId)] to costcenter [$($actionContext.Data.groupId)]"
IsError = $false
})
break
}
'NoChanges' {
Write-Information "No changes to KPN-Mobile-Services account with accountReference: [$($actionContext.References.Account)]"
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = 'No changes will be made to the account during enforcement'
IsError = $false
})
break
}
'NotFound' {
Write-Information "KPN-Mobile-Services account: [$($actionContext.References.Account)] could not be found, possibly indicating that it could be deleted"
$outputContext.Success = $false
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "KPN-Mobile-Services account with accountReference: [$($actionContext.References.Account)] could not be found, possibly indicating that it could be deleted"
IsError = $true
})
break
}
}
}
} catch {
$outputContext.Success = $false
$ex = $PSItem
if ($($ex.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or
$($ex.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$errorObj = Resolve-KPN-Mobile-ServicesError -ErrorObject $ex
$auditMessage = "Could not update KPN-Mobile-Services account. Error: $($errorObj.FriendlyMessage)"
Write-Warning "Error at Line '$($errorObj.ScriptLineNumber)': $($errorObj.Line). Error: $($errorObj.ErrorDetails)"
} else {
$auditMessage = "Could not update KPN-Mobile-Services account. Error: $($ex.Exception.Message)"
Write-Warning "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)"
}
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = $auditMessage
IsError = $true
})
}