-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathenable.ps1
More file actions
467 lines (408 loc) · 20 KB
/
enable.ps1
File metadata and controls
467 lines (408 loc) · 20 KB
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#####################################################
# HelloID-Conn-Prov-Target-Zenya-Enable
# Update account
# PowerShell V2
#####################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
#region functions
function Resolve-ZenyaError {
[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 {
$errorObjectConverted = $httpErrorObj.ErrorDetails | ConvertFrom-Json -ErrorAction Stop
if ($null -ne $errorObjectConverted.detail) {
$errorObjectDetail = [regex]::Matches($errorObjectConverted.detail, '{(.*)}').Value
if ($null -ne $errorObjectDetail) {
try {
$errorDetailConverted = $errorObjectDetail | ConvertFrom-Json -ErrorAction Stop
if ($null -ne $errorDetailConverted) {
if ($null -ne $errorDetailConverted.Error.Message) {
$httpErrorObj.FriendlyMessage = $errorMessage + $errorDetailConverted.Error.Message
}
if ($null -ne $errorDetailConverted.title) {
$httpErrorObj.FriendlyMessage = $errorMessage + $errorDetailConverted.title
}
}
}
catch {
$httpErrorObj.FriendlyMessage = $errorObjectDetail
}
}
else {
$httpErrorObj.FriendlyMessage = $errorObjectConverted.detail
}
if ($null -ne $errorObjectConverted.status) {
$httpErrorObj.FriendlyMessage = $httpErrorObj.FriendlyMessage + " (" + $errorObjectConverted.status + ")"
}
}
else {
$httpErrorObj.FriendlyMessage = $ErrorObject
}
}
catch {
$httpErrorObj.FriendlyMessage = $ErrorObject
}
Write-Output $httpErrorObj
}
}
function Convert-StringToBoolean($obj) {
if ($obj -is [PSCustomObject]) {
foreach ($property in $obj.PSObject.Properties) {
$value = $property.Value
if ($value -is [string]) {
$lowercaseValue = $value.ToLower()
if ($lowercaseValue -eq "true") {
$obj.$($property.Name) = $true
}
elseif ($lowercaseValue -eq "false") {
$obj.$($property.Name) = $false
}
}
elseif ($value -is [PSCustomObject] -or $value -is [System.Collections.IDictionary]) {
$obj.$($property.Name) = Convert-StringToBoolean $value
}
elseif ($value -is [System.Collections.IList]) {
for ($i = 0; $i -lt $value.Count; $i++) {
$value[$i] = Convert-StringToBoolean $value[$i]
}
$obj.$($property.Name) = $value
}
}
}
return $obj
}
#endregion functions
#region account
# Define correlation
$correlationField = "Id"
$correlationValue = $actionContext.References.Account.Id
$account = [PSCustomObject]$actionContext.Data
# Convert the properties containing "TRUE" or "FALSE" to boolean
$account = Convert-StringToBoolean $account
# If option to set department isn't toggled, remove from account object
if ($false -eq $actionContext.Configuration.setDepartment) {
$account.PSObject.Properties.Remove("Department")
}
# If option to set manager isn't toggled, remove from account object
if ($false -eq $actionContext.Configuration.setManager) {
$account.PSObject.Properties.Remove("Manager")
}
else {
$account | Add-Member -MemberType NoteProperty -Name Manager -Value $actionContext.References.ManagerAccount.Id -Force
}
# Define properties to compare for update
$accountPropertiesToCompare = $account.PsObject.Properties.Name
#endRegion account
try {
#region Verify account reference
$actionMessage = "verifying account reference"
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
throw "The account reference could not be found"
}
#endregion Verify account reference
#region Create access token
$actionMessage = "creating access token"
$createAccessTokenBody = @{
grant_type = "client_credentials"
client_id = $actionContext.Configuration.ScimClientId
client_secret = $actionContext.Configuration.ScimClientSecret
token_expiration_disabled = $false
}
$createAccessTokenSplatParams = @{
Uri = "$($actionContext.Configuration.ScimBaseUrl)/oauth/token"
Headers = $headers
Method = "POST"
ContentType = "application/json"
UseBasicParsing = $true
Body = ($createAccessTokenBody | ConvertTo-Json)
Verbose = $false
ErrorAction = "Stop"
}
$createAccessTokenResonse = Invoke-RestMethod @createAccessTokenSplatParams
Write-Information "Created access token. Expires in: $($createAccessTokenResonse.expires_in | ConvertTo-Json)"
#endregion Create access token
#region Create headers
$actionMessage = "creating headers"
$headers = @{
"Accept" = "application/json"
"Content-Type" = "application/json;charset=utf-8"
}
Write-Information "Created headers. Result (without Authorization): $($headers | ConvertTo-Json)."
# Add Authorization after printing splat
$headers['Authorization'] = "$($createAccessTokenResonse.token_type) $($createAccessTokenResonse.access_token)"
#endregion Create headers
#region Get account
# API docs: https://identitymanagement.services.iprova.nl/swagger-ui/#!/scim/GetUserRequest
$actionMessage = "querying Zenya account where [$($correlationField)] = [$($correlationValue)]"
$getZenyaAccountSplatParams = @{
Uri = "$($actionContext.Configuration.ScimBaseUrl)/scim/users/$($actionContext.References.Account.Id)"
Headers = $headers
Method = "GET"
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
Verbose = $false
ErrorAction = "Stop"
}
$getZenyaAccountResponse = Invoke-RestMethod @getZenyaAccountSplatParams
$correlatedAccount = $getZenyaAccountResponse
Write-Information "Queried Zenya account where [$($correlationField)] = [$($correlationValue)]. Result: $($correlatedAccount | ConvertTo-Json)"
#endregion Get account
#region Account
#region Calulate action
$actionMessage = "calculating action"
if (($correlatedAccount | Measure-Object).count -eq 1) {
$outputPreviousData = [PSCustomObject]@{}
$outputPreviousDataObject = $correlatedAccount | Select-Object -First 1
foreach ($prop in $outputPreviousDataObject.PSObject.Properties) {
if ($prop.Name -eq 'emails') {
$outputPreviousData | Add-Member -MemberType NoteProperty -Name 'emails' -Value @($prop.Value.value) -Force
}
elseif ($prop.Name -eq 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User') {
$manager = $prop.Value.manager.value
if ($manager) {
$outputPreviousData | Add-Member -MemberType NoteProperty -Name 'manager' -Value $manager -Force
}
$department = $prop.Value.department
if ($department) {
$outputPreviousData | Add-Member -MemberType NoteProperty -Name 'department' -Value $department -Force
}
}
else {
$outputPreviousData | Add-Member -MemberType NoteProperty -Name $prop.Name -Value $prop.Value -Force
}
}
$outputContext.PreviousData = $outputPreviousData
$actionMessage = "comparing current account to mapped properties"
# Create previous account object to compare current data with specified account data - Only keep properties that are mapped
[PSCustomObject]$previousAccount = $correlatedAccount | Select-Object $account.PSObject.Properties.Name
# Add email as custom object to account object
if ($null -ne $correlatedAccount.Emails) {
$emailsObject = [System.Collections.ArrayList]@()
foreach ($email in $correlatedAccount.Emails) {
if ($email.type -eq "work") {
[void]$emailsObject.Add("work:$($email.value)")
}
}
$previousAccount | Add-Member -MemberType NoteProperty -Name emails -Value $emailsObject -Force
}
# Add department from the extension to previous account object
if ($true -eq $actionContext.Configuration.setDepartment) {
$previousAccount | Add-Member -MemberType NoteProperty -Name "Department" -Value $correlatedAccount."urn:ietf:params:scim:schemas:extension:enterprise:2.0:User".Department -Force
}
# Add manager from the extension to previous account object
if ($true -eq $actionContext.Configuration.setManager) {
$previousAccount | Add-Member -MemberType NoteProperty -Name "Manager" -Value $correlatedAccount."urn:ietf:params:scim:schemas:extension:enterprise:2.0:User".Manager.Value -Force
}
# Create reference object from previous account
$accountReferenceObject = [PSCustomObject]@{}
foreach ($previousAccountProperty in ($previousAccount | Get-Member -MemberType NoteProperty)) {
# Add property using -join to support array values
$accountReferenceObject | Add-Member -MemberType NoteProperty -Name $previousAccountProperty.Name.ToLower() -Value ($previousAccount.$($previousAccountProperty.Name) -join ",") -Force
}
# Create difference object from mapped properties
$accountDifferenceObject = [PSCustomObject]@{}
foreach ($accountProperty in $account.PSObject.Properties) {
# Add property using -join to support array values
$accountDifferenceObject | Add-Member -MemberType NoteProperty -Name $accountProperty.Name.ToLower() -Value ($accountProperty.Value -join ",") -Force
}
$accountSplatCompareProperties = @{
ReferenceObject = $accountReferenceObject.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }
DifferenceObject = $accountDifferenceObject.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }
}
if ($null -ne $accountSplatCompareProperties.ReferenceObject -and $null -ne $accountSplatCompareProperties.DifferenceObject) {
$accountPropertiesChanged = Compare-Object @accountSplatCompareProperties -PassThru
$accountOldProperties = $accountPropertiesChanged | Where-Object { $_.SideIndicator -eq "<=" }
$accountNewProperties = $accountPropertiesChanged | Where-Object { $_.SideIndicator -eq "=>" }
}
if ($accountNewProperties) {
$actionAccount = "Update"
}
else {
$actionAccount = "NoChanges"
}
Write-Information "Compared current account to mapped properties. Result: $actionAccount"
}
elseif (($correlatedAccount | Measure-Object).count -eq 0) {
$actionAccount = "NotFound"
}
elseif (($correlatedAccount | Measure-Object).count -gt 1) {
$actionAccount = "MultipleFound"
}
#endregion Calulate action
#region Process
switch ($actionAccount) {
"Update" {
#region Update account
# API docs: https://identitymanagement.services.iprova.nl/swagger-ui/#!/scim/PatchUser
$actionMessage = "updating account with AccountReference: $($actionContext.References.Account | ConvertTo-Json)"
# Create custom account object for update and set with default properties and values
$updateAccountBody = [PSCustomObject]@{
id = $correlatedAccount.id
operations = @()
}
# Add the updated properties to the custom account object for update
foreach ($accountNewProperty in $accountNewProperties) {
# Add department as extension property to account body
if ($accountNewProperty.Name -eq "Department") {
$updateAccountBody.operations += @{
op = "replace"
path = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:Department"
value = $accountNewProperty.Value
}
}
# Add manager as extension property to account body
elseif ($accountNewProperty.Name -eq "Manager") {
$updateAccountBody.operations += @{
op = "replace"
path = "urn:ietf:params:scim:schemas:extension:enterprise:2.0:User:Manager"
value = $accountNewProperty.Value
}
}
# Transform and add emails to account body
elseif ($accountNewProperty.Name -eq "Emails") {
foreach ($email in $accountNewProperty.Value) {
if ($email.StartsWith("work:")) {
$updateAccountBody.operations += @{
op = "replace"
path = "emails[type eq `"work`"].value"
value = $email -replace "work:", ""
}
}
}
}
else {
$updateAccountBody.operations += @{
op = "replace"
path = $accountNewProperty.name
value = $accountNewProperty.value
}
}
}
$updateAccountSplatParams = @{
Uri = "$($actionContext.Configuration.ScimBaseUrl)/scim/users/$($actionContext.References.Account.Id)"
Method = "PATCH"
Body = ([System.Text.Encoding]::UTF8.GetBytes(($updateAccountBody | ConvertTo-Json -Depth 10)))
ContentType = 'application/json; charset=utf-8'
Verbose = $false
ErrorAction = "Stop"
}
Write-Information "SplatParams: $($updateAccountSplatParams | ConvertTo-Json)"
if (-Not($actionContext.DryRun -eq $true)) {
# Add header after printing splat
$updateAccountSplatParams['Headers'] = $headers
$updateAccountResponse = Invoke-RestMethod @updateAccountSplatParams
$outputData = [PSCustomObject]@{}
$outputObject = $updateAccountResponse | Select-Object -First 1
foreach ($prop in $outputObject.PSObject.Properties) {
if ($prop.Name -eq 'emails') {
$outputData | Add-Member -MemberType NoteProperty -Name 'emails' -Value @($prop.Value.value) -Force
}
elseif ($prop.Name -eq 'urn:ietf:params:scim:schemas:extension:enterprise:2.0:User') {
$manager = $prop.Value.manager.value
if ($manager) {
$outputData | Add-Member -MemberType NoteProperty -Name 'manager' -Value $manager -Force
}
$department = $prop.Value.department
if ($department) {
$outputData | Add-Member -MemberType NoteProperty -Name 'department' -Value $department -Force
}
}
else {
$outputData | Add-Member -MemberType NoteProperty -Name $prop.Name -Value $prop.Value -Force
}
}
$outputContext.Data = $outputData
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Enabled account with AccountReference: $($outputContext.AccountReference | ConvertTo-Json)."
IsError = $false
})
}
else {
Write-Warning "DryRun: Would enable account with AccountReference: $($outputContext.AccountReference | ConvertTo-Json)."
}
#endregion Update account
break
}
"NoChanges" {
#region No changes
$actionMessage = "skipping updating account"
$outputContext.Data = $outputPreviousData
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Skipped update account with AccountReference: $($actionContext.References.Account | ConvertTo-Json). Reason: No changes."
IsError = $false
})
#endregion No changes
break
}
"NotFound" {
#region No account found
$actionMessage = "updating account"
# Throw terminal error
throw "No account found where [$($correlationField)] = [$($correlationValue)]."
#endregion No account found
break
}
"MultipleFound" {
#region Multiple accounts found
$actionMessage = "updating account"
# Throw terminal error
throw "Multiple accounts found where [$($correlationField)] = [$($correlationValue)]. Please correct this to ensure the correlation results in a single unique account."
#endregion Multiple accounts found
break
}
}
#endregion Process
}
catch {
$ex = $PSItem
if ($($ex.Exception.GetType().FullName -eq 'Microsoft.PowerShell.Commands.HttpResponseException') -or
$($ex.Exception.GetType().FullName -eq 'System.Net.WebException')) {
$errorObj = Resolve-ZenyaError -ErrorObject $ex
$auditMessage = "Error $($actionMessage). Error: $($errorObj.FriendlyMessage)"
$warningMessage = "Error at Line [$($errorObj.ScriptLineNumber)]: $($errorObj.Line). Error: $($errorObj.ErrorDetails)"
}
else {
$auditMessage = "Error $($actionMessage). Error: $($ex.Exception.Message)"
$warningMessage = "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)"
}
Write-Warning $warningMessage
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = $auditMessage
IsError = $true
})
}
finally {
# Check if auditLogs contains errors, if no errors are found, set success to true
if ($outputContext.AuditLogs.IsError -contains $true) {
$outputContext.Success = $false
}
else {
$outputContext.Success = $true
}
}