-
Notifications
You must be signed in to change notification settings - Fork 0
/
update.ps1
292 lines (246 loc) · 11.9 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
#################################################
# HelloID-Conn-Prov-Target-SDBHR-Update
# Update account
# PowerShell V2
#################################################
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
#region functions
function Resolve-SDBHRError {
[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 {
# TODO Make sure to inspect the error result object and add only the error message as a FriendlyMessage.
# $errorDetailsObject = ($httpErrorObj.ErrorDetails | ConvertFrom-Json)
# $httpErrorObj.FriendlyMessage = $errorDetailsObject.message
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails # Temporarily assignment
}
catch {
$httpErrorObj.FriendlyMessage = $httpErrorObj.ErrorDetails
}
Write-Output $httpErrorObj
}
}
#endregion functions
#region account
# Define correlation
$correlationField = "Id"
$correlationValue = $actionContext.References.Account
$account = [PSCustomObject]$actionContext.Data
# 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 authentication hash
$actionMessage = "creating authentication hash with Customer Number [$($actionContext.Configuration.CustomerNumber)]"
$currentDateTime = (Get-Date).ToString("dd-MM-yyyy HH:mm:ss.fff")
$baseString = "$($CurrentDateTime.Substring(0,10))|$($CurrentDateTime.Substring(11,12))|$($actionContext.Configuration.CustomerNumber)"
$key = [System.Text.Encoding]::UTF8.GetBytes($actionContext.Configuration.ApiKey)
$hmac256 = [System.Security.Cryptography.HMACSHA256]::new()
$hmac256.key = $key
$hash = $hmac256.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($baseString))
$hashedString = [System.Convert]::ToBase64String($hash)
Write-Information "Created authentication hash with Customer Number [$($actionContext.Configuration.CustomerNumber)]."
#endregion Create authentication hash
#region Create headers
$actionMessage = "creating headers"
$headers = @{
"Klantnummer" = $actionContext.Configuration.CustomerNumber
"Authentication" = "$($actionContext.Configuration.ApiUser):$($hashedString)"
"Timestamp" = $currentDateTime
"Content-Type" = "application/json;charset=utf-8"
"Api-Version" = "2.0"
}
Write-Information "Created headers."
#endregion Create headers
#region Get account
# SDBHR docs: https://api.sdbstart.nl/swagger/ui/index#!/Medewerkers/Medewerkers_GetMedewerkerV2
$getSDBHRAccountSplatParams = @{
Uri = "$($actionContext.Configuration.BaseUri)/medewerkersbasic/$correlationValue"
Headers = $headers
Method = "GET"
ContentType = "application/json;charset=utf-8"
UseBasicParsing = $true
Verbose = $false
ErrorAction = "Stop"
}
$correlatedAccount = Invoke-RestMethod @getSDBHRAccountSplatParams
Write-Information "Queried SDBHR 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 0) {
$actionAccount = "NotFound"
}
elseif (($correlatedAccount | Measure-Object).count -eq 1) {
# Create previous account object to compare current data with specified account data
$previousAccount = $correlatedAccount | Select-Object $accountPropertiesToCompare
$outputContext.PreviousData = $previousAccount
# Calculate changes between current data and provided data
$splatCompareProperties = @{
ReferenceObject = @($previousAccount.PSObject.Properties)
DifferenceObject = @($account.PSObject.Properties | Where-Object { $_.Name -in $accountPropertiesToCompare }) # 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) {
# and update is enabled
# 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) {
$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-Information "Changed properties: $($changedPropertiesObject | ConvertTo-Json)"
$actionAccount = 'Update'
}
else {
Write-Information "No changed properties"
$actionAccount = 'NoChanges'
}
}
elseif (($correlatedAccount | Measure-Object).count -gt 1) {
$actionAccount = "MultipleFound"
}
#endregion Calulate action
#region Process
switch ($actionAccount) {
"Update" {
#region Update account
# SDBHR docs: https://api.sdbstart.nl/swagger/ui/index#!/Medewerkers/Medewerkers_Put
$actionMessage = "updating account"
# Create custom account object for update and set with default properties and values
$updateAccountBody = [PSCustomObject]@{}
# Add the updated properties to the custom account object for update
foreach ($newProperty in $newProperties) {
$updateAccountBody | Add-Member -MemberType NoteProperty -Name $newProperty.Name -Value $newProperty.Value -Force
}
$MutationDate = (Get-Date).ToString("yyyy-MM-dd") # Current Date
$updateAccountSplatParams = @{
Uri = "$($actionContext.Configuration.BaseUri)/medewerkers/$($correlatedAccount.Id)/$($MutationDate)"
Method = "PUT"
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
$updatedAccount = $updateAccountResponse
$outputContext.AccountReference = "$($updatedAccount.id)"
$outputContext.Data = $updatedAccount
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Updated account with AccountReference: $($outputContext.AccountReference | ConvertTo-Json). Updated properties: $($changedPropertiesObject | ConvertTo-Json -Depth 10)."
IsError = $false
})
}
else {
Write-Warning "DryRun: Would update account with AccountReference: $($outputContext.AccountReference | ConvertTo-Json). Updated properties: $($changedPropertiesObject | ConvertTo-Json -Depth 10)."
}
#endregion Update account
break
}
"NoChanges" {
#region No changes
$actionMessage = "skipping updating account"
$outputContext.Data = $correlatedAccount
$outputContext.AuditLogs.Add([PSCustomObject]@{
# Action = "" # Optional
Message = "Skipped updating account with AccountReference: $($actionContext.References.Account | ConvertTo-Json). Reason: No changes."
IsError = $false
})
#endregion No changes
break
}
"MultipleFound" {
#region Multiple accounts found
$actionMessage = "updating account"
# Throw terminal error
throw "Multiple accounts found where [$($correlationField)] = [$($correlationValue)]. Please correct this so the persons are unique."
#endregion Multiple accounts found
break
}
"NotFound" {
#region No account found
$actionMessage = "updating account"
# Throw terminal error
throw "No account found where [$($correlationField)] = [$($correlationValue)] while this connector only supports correlation."
#endregion No account 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-SDBHRError -ErrorObject $ex
$auditMessage = "Error $($actionMessage). Error: $($errorObj.FriendlyMessage)"
Write-Warning "Error at Line [$($errorObj.ScriptLineNumber)]: $($errorObj.Line). Error: $($errorObj.ErrorDetails)"
}
else {
$auditMessage = "Error $($actionMessage). Error: $($ex.Exception.Message)"
Write-Warning "Error at Line [$($ex.InvocationInfo.ScriptLineNumber)]: $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)"
}
$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
}
# Check if accountreference is set, if not set, set this with default value as this must contain a value
if ([String]::IsNullOrEmpty($outputContext.AccountReference) -and $actionContext.DryRun -eq $true) {
$outputContext.AccountReference = "DryRun: Currently not available"
}
}