-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.ps1
368 lines (311 loc) · 15.4 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
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
#################################################
# HelloID-Conn-Prov-Target-RAET-Beaufort-IAM-API-Contact-Details-Update
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
# Set debug logging
switch ($($actionContext.Configuration.isDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
# Used to connect to RAET IAM API endpoints
$Script:AuthenticationUri = "https://connect.visma.com/connect/token"
$Script:BaseUri = "https://api.youforce.com"
#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 # Does not show the correct error message for the Raet IAM API calls
$httpErrorObj.ErrorMessage = $ErrorObject.Exception.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 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 -Error $ErrorObject
$errorMessage.VerboseErrorMessage = $httpErrorObject.ErrorMessage
$errorMessage.AuditErrorMessage = $httpErrorObject.ErrorMessage
}
# 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
}
}
function New-RaetSession {
[CmdletBinding()]
param (
[Alias("Param1")]
[parameter(Mandatory = $true)]
[string]
$ClientId,
[Alias("Param2")]
[parameter(Mandatory = $true)]
[string]
$ClientSecret,
[Alias("Param3")]
[parameter(Mandatory = $false)]
[string]
$TenantId
)
#Check if the current token is still valid
$accessTokenValid = Confirm-AccessTokenIsValid
if ($true -eq $accessTokenValid) {
return
}
try {
# Set TLS to accept TLS, TLS 1.1 and TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
$authorisationBody = @{
'grant_type' = "client_credentials"
'client_id' = $ClientId
'client_secret' = $ClientSecret
'tenant_id' = $TenantId
}
$splatAccessTokenParams = @{
Uri = $Script:AuthenticationUri
Headers = @{'Cache-Control' = "no-cache" }
Method = 'POST'
ContentType = "application/x-www-form-urlencoded"
Body = $authorisationBody
UseBasicParsing = $true
}
Write-Verbose "Creating Access Token at uri '$($splatAccessTokenParams.Uri)'"
$result = Invoke-RestMethod @splatAccessTokenParams -Verbose:$false
if ($null -eq $result.access_token) {
throw $result
}
$Script:expirationTimeAccessToken = (Get-Date).AddSeconds($result.expires_in)
$Script:AuthenticationHeaders = @{
'Authorization' = "Bearer $($result.access_token)"
'Accept' = "application/json"
}
Write-Verbose "Successfully created Access Token at uri '$($splatAccessTokenParams.Uri)'"
}
catch {
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($($errorMessage.VerboseErrorMessage))"
throw "Error creating Access Token at uri ''$($splatAccessTokenParams.Uri)'. Please check credentials. Error Message: $($errorMessage.AuditErrorMessage)"
}
}
function Confirm-AccessTokenIsValid {
if ($null -ne $Script:expirationTimeAccessToken) {
if ((Get-Date) -le $Script:expirationTimeAccessToken) {
return $true
}
}
return $false
}
#endregion functions
try {
if (($actionContext.AccountCorrelated -eq $true) -or ($actionContext.Configuration.onlyUpdateOnCorrelate -eq $false)) {
#region account
# Define account object
$account = [PSCustomObject]$actionContext.Data
# Remove personCode field because only used for export data
$account = $account | Select-Object -ExcludeProperty personCode
# Define properties to compare for update
$accountPropertiesToCompare = $account.PsObject.Properties.Name
#endRegion account
# Verify if [aRef] has a value
if ([string]::IsNullOrEmpty($($actionContext.References.Account))) {
throw 'The account reference could not be found'
}
$accessTokenValid = Confirm-AccessTokenIsValid
if ($true -ne $accessTokenValid) {
$splatRaetSession = @{
ClientId = $actionContext.Configuration.clientId
ClientSecret = $actionContext.Configuration.clientSecret
TenantId = $actionContext.Configuration.tenantId
}
New-RaetSession @splatRaetSession
}
Write-Verbose "Verifying if a Raet Beaufort employee account for [$($personContext.Person.DisplayName)] exists"
$splatWebRequest = @{
Uri = "$($Script:BaseUri)/iam/v1.0/persons/$($actionContext.References.Account)"
Headers = $Script:AuthenticationHeaders
Method = 'GET'
ContentType = "application/json"
UseBasicParsing = $true
}
try {
$correlatedAccount = Invoke-RestMethod @splatWebRequest -Verbose:$false
}
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 "*Not Found*" -or $errorMessage.AuditErrorMessage -Like "No employee found in Raet Beaufort with $($correlationProperty) '$($correlationValue)'") {
write-verbose "No employee found in Raet Beaufort with personCode [$($actionContext.References.Account)]. Possibly already deleted."
$correlatedAccount = $null
}
else {
throw $_
}
}
$outputContext.PreviousData.personCode = $correlatedAccount.personCode
# Always compare the account against the current account in target system
if ($null -ne $correlatedAccount.id) {
# Get value of current Business Email Address
if ($null -ne $correlatedAccount.emailAddresses) {
$businessEmailAddress = $correlatedAccount.emailAddresses | Where-Object { $_.type -eq "Business" }
$businessEmailAddressValue = $businessEmailAddress.address
}
# Get value of current Business Phonenumber
if ($null -ne $correlatedAccount.phoneNumbers) {
$businessPhoneNumber = $correlatedAccount.phoneNumbers | Where-Object { $_.type -eq "Business" }
$businessPhoneNumberValue = $businessPhoneNumber.number
}
# Retrieve current account data for properties to be updated
$previousAccount = [PSCustomObject]@{
'emailAddress' = $businessEmailAddressValue
'phoneNumber' = $businessPhoneNumberValue
}
if (-not($actionContext.Data.PSObject.Properties.Name -Contains 'emailAddress')) {
$previousAccount.PSObject.Properties.Remove('emailAddress')
}
else {
$outputContext.PreviousData.emailAddress = $previousAccount.emailAddress
}
if (-not($actionContext.Data.PSObject.Properties.Name -Contains 'phoneNumber')) {
$previousAccount.PSObject.Properties.Remove('phoneNumber')
}
else {
$outputContext.PreviousData.phoneNumber = $previousAccount.phoneNumber
}
$splatCompareProperties = @{
ReferenceObject = $previousAccount.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }
DifferenceObject = $account.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }
}
if ($null -ne $splatCompareProperties.ReferenceObject -and $null -ne $splatCompareProperties.DifferenceObject) {
$accountPropertiesChanged = Compare-Object @splatCompareProperties -PassThru
$accountOldProperties = $accountPropertiesChanged | Where-Object { $_.SideIndicator -eq "<=" }
$accountNewProperties = $accountPropertiesChanged | Where-Object { $_.SideIndicator -eq "=>" }
}
if ($accountNewProperties) {
$action = 'Update'
Write-Information "Account property(s) required to update: $($accountNewProperties.Name -join ', ')"
}
else {
$action = 'NoChanges'
}
}
else {
$action = 'NotFound'
}
# Process
switch ($action) {
'Update' {
Write-Verbose "Updating Raet Beaufort employee account with accountReference: [$($actionContext.References.Account)]"
# Create custom object with old and new values (for logging)
$accountChangedPropertiesObject = [PSCustomObject]@{
OldValues = @{}
NewValues = @{}
}
foreach ($accountOldProperty in ($accountOldProperties | Where-Object { $_.Name -in $accountNewProperties.Name })) {
$accountChangedPropertiesObject.OldValues.$($accountOldProperty.Name) = $accountOldProperty.Value
}
foreach ($accountNewProperty in $accountNewProperties) {
$accountChangedPropertiesObject.NewValues.$($accountNewProperty.Name) = $accountNewProperty.Value
}
$body = ($account | ConvertTo-Json -Depth 10)
$splatWebRequest = @{
Uri = "$($Script:BaseUri)/iam/v1.0/ContactDetails/$($actionContext.References.Account)"
Headers = $Script:AuthenticationHeaders
Method = 'POST'
Body = ([System.Text.Encoding]::UTF8.GetBytes($body))
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
}
if ($actionContext.DryRun -eq $true) {
Write-Warning "DryRun: Would update account with AccountReference: $($actionContext.References.Account | ConvertTo-Json). Old values: $($accountChangedPropertiesObject.oldValues | ConvertTo-Json). New values: $($accountChangedPropertiesObject.newValues | ConvertTo-Json)"
}
else {
$updatedAccount = Invoke-RestMethod @splatWebRequest -Verbose:$false
$outputContext.Data.personCode = $updatedAccount.contactDetails.personCode
if ($actionContext.Data.PSObject.Properties.Name -Contains 'emailAddress') {
$outputContext.Data.emailAddress = $updatedAccount.contactDetails.emailAddress
}
if ($actionContext.Data.PSObject.Properties.Name -Contains 'phoneNumber') {
$outputContext.Data.phoneNumber = $updatedAccount.contactDetails.phoneNumber
}
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Update account was successful, Account property(s) updated: Old values: $($accountChangedPropertiesObject.oldValues | ConvertTo-Json). New values: $($accountChangedPropertiesObject.newValues | ConvertTo-Json)"
IsError = $false
})
}
break
}
'NoChanges' {
Write-Verbose "No changes to Raet Beaufort employee account with accountReference: [$($actionContext.References.Account)]"
$outputContext.Data.personCode = $correlatedAccount.personCode
$outputContext.Success = $true
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = 'No changes will be made to the account during enforcement'
IsError = $false
})
break
}
'NotFound' {
$outputContext.Success = $false
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = "Raet Beaufort employee account [$($actionContext.References.Account)] for: [$($personContext.Person.DisplayName)] could not be found, possibly indicating that it could be deleted, or the account is not correlated"
IsError = $true
})
break
}
}
}
else {
$outputContext.Success = $true
Write-Verbose "The configuration parameter only update on correlate is [$($actionContext.Configuration.onlyUpdateOnCorrelate)]"
}
}
catch {
$outputContext.Success = $false
$ex = $PSItem
$errorMessage = Get-ErrorMessage -ErrorObject $ex
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($($errorMessage.VerboseErrorMessage))"
$auditMessage = "Could not update Raet Beaufort employee account. Error Message: $($errorMessage.AuditErrorMessage)"
$outputContext.AuditLogs.Add([PSCustomObject]@{
Message = $auditMessage
IsError = $true
})
}