-
Notifications
You must be signed in to change notification settings - Fork 0
/
enable.ps1
358 lines (313 loc) · 12.2 KB
/
enable.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
#################################################
# HelloID-Conn-Prov-Target-Ecare-Enable
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
#region functions
function Get-GenericScimOAuthToken {
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$ClientID,
[Parameter(Mandatory = $true)]
[string]
$ClientSecret,
[Parameter(Mandatory = $true)]
[string]
$TokenUrl
)
try {
$headers = @{
"content-type" = "application/x-www-form-urlencoded"
}
$body = @{
client_id = $ClientID
client_secret = $ClientSecret
grant_type = "client_credentials"
scope = "Ecare.Service.SCIM"
}
$splatParams = @{
Uri = "$($TokenUrl)/connect/token"
Method = 'POST'
Headers = $headers
Body = $body
}
$Response = Invoke-RestMethod @splatParams
Write-Output $Response.access_token
}
catch {
$PSCmdlet.ThrowTerminatingError($PSItem)
}
}
function Invoke-EcareRestMethod {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$Method,
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[string]
$Uri,
[object]
$Body,
[string]
$ContentType = 'application/json',
[Parameter(Mandatory = $false)]
[System.Collections.IDictionary]
$Headers = @{}
)
process {
try {
$splatParams = @{
Uri = $Uri
Headers = $headers
Method = $Method
ContentType = $ContentType
}
if ($Body){
$splatParams['Body'] = $Body
}
Invoke-RestMethod @splatParams -Verbose:$false
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
}
function ConvertTo-AccountObject {
param(
[parameter(Mandatory)]
[PSCustomObject]
$AccountModel,
[parameter( Mandatory,
ValueFromPipeline = $True)]
[PSCustomObject]
$SourceObject
)
try {
$modifiedObject = [PSCustomObject]@{}
foreach ($property in $AccountModel.PSObject.Properties) {
if($property.Name -eq 'employeeNumber') {
$modifiedObject | Add-Member @{ $($property.Name) = $SourceObject.$('urn:ietf:params:scim:schemas:extension:enterprise:2.0:User').$($property.Name) }
}
elseif ($property.Name -eq 'WorkEmail') {
foreach ($email in $SourceObject.emails) {
if ($email.type -eq "work") {
$modifiedObject | Add-Member @{ $($property.Name) = $email.value}
break
}
}
}
else {
$modifiedObject | Add-Member @{ $($property.Name) = $SourceObject.$($property.Name) }
}
}
Write-Output $modifiedObject
} catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
function Resolve-EcareError {
[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.
# $httpErrorObj.FriendlyMessage = $errorDetailsObject.message
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails # Temporarily assignment
} catch {
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails
}
Write-Output $httpErrorObj
}
}
function ConvertTo-ScimUpdateObject {
[CmdletBinding()]
param (
[Parameter(
Mandatory,
ValueFromPipeline = $True,
Position = 0)]
$EcareAccount
)
[System.Collections.Generic.List[object]]$operations = @()
foreach ($property in $EcareAccount.PSObject.Properties) {
if ($property.Name -eq "WorkEmail") {
$operations.Add(
[PSCustomObject]@{
op = "Replace"
path = "emails"
value = $property.Value
}
)
} else {
$operations.Add(
[PSCustomObject]@{
op = "Replace"
path = $property.Name
value = $property.Value
}
)
}
}
$body = [ordered]@{
schemas = @(
"urn:ietf:params:scim:api:messages:2.0:PatchOp"
)
Operations = $operations
}
write-output $body
}
#endregion
try {
# Verify if [aRef] has a value
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
throw 'The account reference could not be found'
}
$accessToken = Get-GenericScimOAuthToken -ClientID $ActionContext.Configuration.ClientId -ClientSecret $ActionContext.Configuration.ClientSecret -TokenUrl $ActionContext.Configuration.tokenUrl
$headers = @{
Authorization = "Bearer $accessToken"
}
Write-Information "Verifying if a Ecare account for [$($personContext.Person.DisplayName)] exists"
try {
$splatParams = @{
Uri = "$($actionContext.Configuration.BaseUrl)/scim/Users/$($actionContext.References.Account)"
Method = 'GET'
Headers = $headers
}
$correlatedAccount = Invoke-EcareRestMethod @splatParams
$outputContext.PreviousData = $correlatedAccount
} catch {
if ($_.Exception.Response.StatusCode -eq 404){
$action = 'NotFound'
} else {
throw $_
}
}
if ($null -ne $correlatedAccount) {
$splatCompareProperties = @{
ReferenceObject = @($correlatedAccount.PSObject.Properties)
DifferenceObject = @(([PSCustomObject]$actionContext.Data).PSObject.Properties)
}
$propertiesChanged = Compare-Object @splatCompareProperties -PassThru | Where-Object { $_.SideIndicator -eq '=>' }
if ($propertiesChanged) {
$action = 'UpdateEnableAccount'
$dryRunMessage = "Update and enable Ecare account: [$($actionContext.References.Account)] for person: [$($personContext.Person.DisplayName)] will be executed during enforcement"
}
else
{
$action = 'EnableAccount'
$dryRunMessage = "Enable Ecare account: [$($actionContext.References.Account)] for person: [$($personContext.Person.DisplayName)] will be executed during enforcement"
}
} else {
$action = 'NotFound'
$dryRunMessage = "Ecare account: [$($actionContext.References.Account)] for person: [$($personContext.Person.DisplayName)] could not be found, possibly indicating that it could be deleted, or the account is not correlated"
}
# Add a message and the result of each of the validations showing what will happen during enforcement
if ($actionContext.DryRun -eq $true) {
Write-Information "[DryRun] $dryRunMessage"
}
# Process
if (-not($actionContext.DryRun -eq $true)) {
switch ($action) {
'EnableAccount' {
Write-Information "Enabling Ecare account with accountReference: [$($actionContext.References.Account)]"
[System.Collections.Generic.List[object]]$operations = @()
$operations.Add(
[PSCustomObject]@{
op = "Replace"
path = "active"
value = $True
}
)
$body = [ordered]@{
schemas = @(
"urn:ietf:params:scim:api:messages:2.0:PatchOp"
)
Operations = $operations
}
$splatParams = @{
Uri = "$($actionContext.Configuration.BaseUrl)/scim/Users/$($actionContext.References.Account)"
Body = $body | ConvertTo-Json
Method = 'PATCH'
Headers = $headers
}
$null = Invoke-EcareRestMethod @splatParams
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = 'Enable account was successful'
IsError = $false
})
break
}
'UpdateEnableAccount' {
Write-Information "Updating and disabling Ecare account with accountReference: [$($actionContext.References.Account)]"
# Make sure to test with special characters and if needed; add utf8 encoding.
$ecareUpdateAccount = $actionContext.Data | Select-Object -Property $propertiesChanged.Name
$body = $ecareUpdateAccount | ConvertTo-ScimUpdateObject
$splatParams = @{
Uri = "$($actionContext.Configuration.BaseUrl)/scim/Users/$($actionContext.References.Account)"
Body = $body | ConvertTo-Json
Method = 'Patch'
Headers = $headers
}
$UpdateResult = Invoke-EcareRestMethod @splatParams
$outputContext.data = $actionContext.Data
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Update and disable account was successful, Account property(s) updated: [$($propertiesChanged.name -join ',')]"
IsError = $false
})
break
}
'NotFound' {
$outputContext.Success = $false
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Ecare account: [$($actionContext.References.Account)] for person: [$($personContext.Person.DisplayName)] could not be found, possibly indicating that it could be deleted, or the account is not correlated"
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-EcareError -ErrorObject $ex
$auditMessage = "Could not enable Ecare account. Error: $($errorObj.FriendlyMessage)"
Write-Warning "Error at Line '$($errorObj.ScriptLineNumber)': $($errorObj.Line). Error: $($errorObj.ErrorDetails)"
} else {
$auditMessage = "Could not enable Ecare account. Error: $($_.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
})
}