-
Notifications
You must be signed in to change notification settings - Fork 0
/
disable.ps1
414 lines (360 loc) · 17.2 KB
/
disable.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
#####################################################
# HelloID-Conn-Prov-Target-AFAS-Profit-Users-Disable
# PowerShell V2
#####################################################
# Set to false at start, at the end, only when no error occurs it is set to true
$outputContext.Success = $false
# AccountReference must have a value for dryRun
$outputContext.AccountReference = $actionContext.References.Account
# Set debug logging
switch ($($actionContext.Configuration.isDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
#region functions
function Resolve-HTTPError {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$httpErrorObj = [PSCustomObject]@{
FullyQualifiedErrorId = $ErrorObject.FullyQualifiedErrorId
MyCommand = $ErrorObject.InvocationInfo.MyCommand
RequestUri = $ErrorObject.TargetObject.RequestUri
ScriptStackTrace = $ErrorObject.ScriptStackTrace
ErrorMessage = ''
}
if ($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') {
$httpErrorObj.ErrorMessage = $ErrorObject.ErrorDetails.Message
}
elseif ($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException') {
$httpErrorObj.ErrorMessage = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
}
Write-Output $httpErrorObj
}
}
function Resolve-AFASErrorMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
try {
$errorObjectConverted = $ErrorObject | ConvertFrom-Json -ErrorAction Stop
if ($null -ne $errorObjectConverted.externalMessage) {
$errorMessage = $errorObjectConverted.externalMessage
}
else {
$errorMessage = $errorObjectConverted
}
}
catch {
$errorMessage = "$($ErrorObject.Exception.Message)"
}
Write-Output $errorMessage
}
}
function Get-ErrorMessage {
[CmdletBinding()]
param (
[Parameter(Mandatory,
ValueFromPipeline
)]
[object]$ErrorObject
)
process {
$errorMessage = [PSCustomObject]@{
VerboseErrorMessage = $null
AuditErrorMessage = $null
}
if ( $($ErrorObject.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or $($ErrorObject.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$httpErrorObject = Resolve-HTTPError -ErrorObject $ErrorObject
if (-not[String]::IsNullOrEmpty($httpErrorObject.ErrorMessage)) {
$errorMessage.VerboseErrorMessage = $httpErrorObject.ErrorMessage
$errorMessage.AuditErrorMessage = Resolve-AFASErrorMessage -ErrorObject $httpErrorObject.ErrorMessage
}
else {
$errorMessage.VerboseErrorMessage = $ErrorObject.Exception.Message
$errorMessage.AuditErrorMessage = $ErrorObject.Exception.Message
}
}
# If error message empty, fall back on $ex.Exception.Message
if ([String]::IsNullOrEmpty($errorMessage.VerboseErrorMessage)) {
$errorMessage.VerboseErrorMessage = $ErrorObject.Exception.Message
}
if ([String]::IsNullOrEmpty($errorMessage.AuditErrorMessage)) {
$errorMessage.AuditErrorMessage = $ErrorObject.Exception.Message
}
Write-Output $errorMessage
}
}
#endregion functions
try {
# Correlation values
$correlationProperty = "Gebruiker" # Has to match the name of the unique identifier
$correlationValue = $actionContext.References.Account.Gebruiker # Has to match the value of the unique identifier
$account = $actionContext.Data
# Remove field because only used for export data or to set correlation
if ($account.PSObject.Properties.Name -Contains 'Gebruiker') {
$account.PSObject.Properties.Remove('Gebruiker')
}
if ($account.PSObject.Properties.Name -Contains 'Medewerker') {
$account.PSObject.Properties.Remove('Medewerker')
}
$updateAccountFields = @()
if ($account.PSObject.Properties.Name -Contains 'EmAd') {
$updateAccountFields += "EmAd"
}
if ($account.PSObject.Properties.Name -Contains 'Upn') {
$updateAccountFields += "Upn"
}
if ($account.PSObject.Properties.Name -Contains 'Site') {
$updateAccountFields += "Site"
}
if ($account.PSObject.Properties.Name -Contains 'InSi') {
$updateAccountFields += "InSi"
}
# Verify if [aRef] has a value
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "The account reference could not be found"
IsError = $true
})
throw 'The account reference could not be found'
}
# Get current account and verify if there are changes
try {
Write-Verbose "Querying AFAS user where [$($correlationProperty)] = [$($correlationValue)]"
# Create authorization headers
$encodedToken = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($($actionContext.Configuration.Token)))
$authValue = "AfasToken $encodedToken"
$Headers = @{ Authorization = $authValue }
$Headers.Add("IntegrationId", "45963_140664") # Fixed value - Tools4ever Partner Integration ID
$splatWebRequest = @{
Uri = "$($actionContext.Configuration.BaseUri)/connectors/$($actionContext.Configuration.GetConnector)?filterfieldids=$($correlationProperty)&filtervalues=$($correlationValue)&operatortypes=1"
Headers = $headers
Method = 'GET'
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
}
$currentAccount = (Invoke-RestMethod @splatWebRequest -Verbose:$false).rows
if ($null -eq $currentAccount.Gebruiker) {
throw "No AFAS user found where [$($correlationProperty)] = [$($correlationValue)]"
}
else {
# Create previous account object to compare current data with specified account data
$previousAccount = [PSCustomObject]@{
# E-mail
'EmAd' = $currentAccount.Email_werk_gebruiker
# UPN
'Upn' = $currentAccount.UPN
# Outsite
"Site" = [String]$currentAccount.OutSite
# InSite
"InSi" = [String]$currentAccount.InSite
}
# Calculate changes between current data and provided data
$splatCompareProperties = @{
ReferenceObject = @($previousAccount.PSObject.Properties | Where-Object { $_.Name -in $updateAccountFields }) # Only select the properties to update
DifferenceObject = @($account.PSObject.Properties | Where-Object { $_.Name -in $updateAccountFields }) # Only select the properties to update
}
$changedProperties = $null
$changedProperties = (Compare-Object @splatCompareProperties -PassThru)
$oldProperties = $changedProperties.Where( { $_.SideIndicator -eq '<=' })
$newProperties = $changedProperties.Where( { $_.SideIndicator -eq '=>' })
if (($newProperties | Measure-Object).Count -ge 1) {
Write-Verbose "Changed properties: $($changedProperties | ConvertTo-Json)"
$updateAction = 'Update'
}
else {
Write-Verbose "No changed properties"
$updateAction = 'NoChanges'
}
}
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
if ($errorMessage.AuditErrorMessage -Like "*No AFAS user found*") {
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "No AFAS user found where [$($correlationProperty)] = [$($aRef.Gebruiker)]. Possibly already deleted, skipping action."
IsError = $false
})
}
else {
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "Error querying AFAS user where [$($correlationProperty)] = [$($aRef.Gebruiker)]. Error Message: $($errorMessage.AuditErrorMessage)"
IsError = $true
})
}
# Skip further actions, as this is a critical error
throw "Error querying AFAS user"
}
# Disable AFAS User
try {
# Create custom account object for disable and set with properties for disable only
$disableAccount = [PSCustomObject]@{
'KnUser' = @{
'Element' = @{
# Gebruiker
'@UsId' = $currentAccount.Gebruiker
'Fields' = @{
# Mutatie code
'MtCd' = $account.MtCd
# Omschrijving
"Nm" = $currentAccount.DisplayName
}
}
}
}
$body = ($disableAccount | ConvertTo-Json -Depth 10)
$splatWebRequest = @{
Uri = "$($actionContext.Configuration.BaseUri)/connectors/$($actionContext.Configuration.UpdateConnector)"
Headers = $headers
Method = 'PUT'
Body = ([System.Text.Encoding]::UTF8.GetBytes($body))
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
}
if (-Not($actionContext.DryRun -eq $true)) {
Write-Verbose "Disabling AFAS user [$($currentAccount.Gebruiker)]"
$disabledAccount = Invoke-RestMethod @splatWebRequest -Verbose:$false
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "Successfully disabled AFAS user [$($currentAccount.Gebruiker)]"
IsError = $false
})
}
else {
Write-Warning "DryRun: Would disable AFAS user [$($currentAccount.Gebruiker)]"
}
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "Error disabling AFAS user [$($currentAccount.Gebruiker)]. Error Message: $($errorMessage.AuditErrorMessage)"
IsError = $true
})
# Skip further actions, as this is a critical error
throw "Error disabling AFAS user"
}
switch ($updateAction) {
'Update' {
# Update AFAS User
try {
# Create custom object with old and new values
$changedPropertiesObject = [PSCustomObject]@{
OldValues = @{}
NewValues = @{}
}
# Add the old properties to the custom object with old and new values
foreach ($oldProperty in ($oldProperties | Where-Object { $_.Name -in $newProperties.Name })) {
$changedPropertiesObject.OldValues.$($oldProperty.Name) = $oldProperty.Value
}
# Add the new properties to the custom object with old and new values
foreach ($newProperty in $newProperties) {
$changedPropertiesObject.NewValues.$($newProperty.Name) = $newProperty.Value
}
Write-Verbose "Changed properties: $($changedPropertiesObject | ConvertTo-Json)"
# Create custom account object for update and set with default properties and values
$updateAccount = [PSCustomObject]@{
'KnUser' = @{
'Element' = @{
# Gebruiker
'@UsId' = $currentAccount.Gebruiker
'Fields' = @{
# Mutatie code
'MtCd' = $account.MtCd
# Omschrijving
"Nm" = $currentAccount.DisplayName
}
}
}
}
# Add the updated properties to the custom account object for update
foreach ($newProperty in $newProperties) {
$updateAccount.KnUser.Element.Fields.$($newProperty.Name) = $newProperty.Value
}
$body = ($updateAccount | ConvertTo-Json -Depth 10)
$splatWebRequest = @{
Uri = "$($actionContext.Configuration.BaseUri)/connectors/$($actionContext.Configuration.UpdateConnector)"
Headers = $headers
Method = 'PUT'
Body = ([System.Text.Encoding]::UTF8.GetBytes($body))
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
}
if (-Not($actionContext.DryRun -eq $true)) {
Write-Verbose "Updating AFAS user [$($currentAccount.Gebruiker)]. Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
$updatedAccount = Invoke-RestMethod @splatWebRequest -Verbose:$false
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "Successfully updated AFAS user [$($currentAccount.Gebruiker)]. Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
IsError = $false
})
}
else {
Write-Warning "DryRun: Would update AFAS user [$($currentAccount.Gebruiker)]. Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
}
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($errorMessage.VerboseErrorMessage)"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "Error updating AFAS user [$($currentAccount.Gebruiker)]. Error Message: $($errorMessage.AuditErrorMessage). Old values: $($changedPropertiesObject.oldValues | ConvertTo-Json -Depth 10). New values: $($changedPropertiesObject.newValues | ConvertTo-Json -Depth 10)"
IsError = $true
})
# Skip further actions, as this is a critical error
throw "Error updating AFAS user"
}
break
}
'NoChanges' {
# Only log when fields are selected to update
if (($updateAccountFields | Measure-Object).Count -ge 1) {
Write-Verbose "No changes needed for AFAS user [$($currentAccount.Gebruiker)]"
if (-Not($actionContext.DryRun -eq $true)) {
$outputContext.AuditLogs.Add([PSCustomObject]@{
Action = "DisableAccount"
Message = "No changes needed for AFAS user [$($currentAccount.Gebruiker)]"
IsError = $false
})
}
else {
Write-Warning "DryRun: No changes needed for AFAS user [$($currentAccount.Gebruiker)]"
}
}
break
}
}
}
catch {
$ex = $PSItem
Write-Verbose "ERROR: $ex"
}
finally {
# Check if auditLogs contains errors, if no errors are found, set success to true
if (-NOT($outputContext.AuditLogs.IsError -contains $true)) {
$outputContext.Success = $true
}
$outputContext.Data = $account
$outputContext.PreviousData = $previousAccount
}