-
Notifications
You must be signed in to change notification settings - Fork 0
/
create.ps1
368 lines (322 loc) · 13.5 KB
/
create.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-Nedap-AEOS-Create
#
# Version: 1.1.0
#####################################################
# Initialize default values
$config = $configuration | ConvertFrom-Json
$p = $person | ConvertFrom-Json
$success = $false
$auditLogs = [System.Collections.Generic.List[PSCustomObject]]::new()
function New-AeosName {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[ValidateNotNullOrEmpty()]
[object]
$person
)
if ([string]::IsNullOrEmpty($person.Name.Initials)) {
$initials = $person.Name.Initials
}
else {
$initials = $person.Name.Initials[0..9] -join "" # Max 10 chars
}
if ([string]::IsNullOrEmpty($person.Name.FamilyNamePrefix)) {
$prefix = ""
}
else {
$prefix = $person.Name.FamilyNamePrefix + " "
}
if ([string]::IsNullOrEmpty($person.Name.FamilyNamePartnerPrefix)) {
$partnerPrefix = ""
}
else {
$partnerPrefix = $person.Name.FamilyNamePartnerPrefix + " "
}
$AeosSurname = switch ($person.Name.Convention) {
"B" { $person.Name.FamilyName }
"BP" { $person.Name.FamilyName + " - " + $partnerprefix + $person.Name.FamilyNamePartner }
"P" { $person.Name.FamilyNamePartner }
"PB" { $person.Name.FamilyNamePartner + " - " + $prefix + $person.Name.FamilyName }
default { $prefix + $person.Name.FamilyName }
}
$AeosPrefix = switch ($person.Name.Convention) {
"B" { $prefix }
"BP" { $prefix }
"P" { $partnerPrefix }
"PB" { $partnerPrefix }
default { $prefix }
}
$output = [PSCustomObject]@{
prefixes = $AeosPrefix
surname = $AeosSurname
initials = $Initials
}
Write-Output $output
}
function format-date {
[CmdletBinding()]
Param
(
[string]$date,
[string]$InputFormat,
[string]$OutputFormat
)
try {
if (-NOT([string]::IsNullOrEmpty($date))) {
$dateString = get-date([datetime]::ParseExact($date, $InputFormat, $null)).ToUniversalTime() -Format($OutputFormat)
$dateString = $dateString.Replace("T12", "T00")
}
else {
$dateString = $null
}
return $dateString
}
catch {
throw("An error was thrown while formatting date: $($_.Exception.Message): $($_.ScriptStackTrace)")
}
}
# Account mapping
$account = [PSCustomObject]@{
Id = $null # autogenerated, but leave dummy in account object to ensure that it will be the first attribute
ArrivalDateTime = (format-date ($p.PrimaryContract.StartDate) "yyyy-MM-ddThh:mm:ssZ" "yyyy-MM-ddThh:mm:ss") # 2018-11-25T15:44:07 <!-- XSD DateTime data type format --> Set to a date in the far future to create account as disabled
LeaveDateTime = "2099-01-01T00:00:00" # empty string does not clear value, so fill in a time far in the future.
LastName = (New-AeosName -Person $p).surname # <!-- String, max. 50 characters -->
PersonnelNo = $p.ExternalId # <!-- String, max. 50 characters -->
FirstName = $p.Name.GivenName # <!-- String, max. 40 characters -->
MiddleName = (New-AeosName -Person $p).prefixes
Gender = "Unknown" # <!-- Male, Female, Unknown -->
Email = $p.Accounts.MicrosoftActiveDirectory.mail # <!-- String, max. 128 characters -->
Language = "nl" # <!-- ar, de, dk, en, es, fa, fr, it, iw, nl, no, pl, pt, ru, sv,zh_CN --> <!-- String, max. 12 characters (but most are unused) -->
# NetworkId = $null # autogenerated?
# CarrierType = $null # autogenerated?
# UnitId = $null # autogenerated?
# NrMovements = $null
# ReadOnly = $null
# FreeField = $null # list of objects with free fields {DefinitionId,Name,Value}, currently not supported in this connector
# Title = $null # <!-- String, max. 25 characters -->
# PhoneNo = $null # <!-- String, max. 25 characters --> <!-- Do not use spaces or hyphens if dialers (such as SMS servers) need to process this phone number. -->
# MobilePhoneNo = $null # <!-- String, max. 25 characters -->
# ContactPersonId = $null # <!-- Long. You can find this ID with findPerson -->
# DepartmentId = $null # <!-- Long. You can find this ID with findDepartment -->
}
# Enable TLS1.2
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor [System.Net.SecurityProtocolType]::Tls12
# Set debug logging
switch ($($config.IsDebug)) {
$true { $VerbosePreference = 'Continue' }
$false { $VerbosePreference = 'SilentlyContinue' }
}
$updatePerson = [boolean]($config.UpdateOnCorrelate)
#region functions
function New-SoapbodyFindEmployee {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[PSCustomObject] $Account
)
[system.text.StringBuilder] $soapFindEmployee = [system.text.StringBuilder]::new()
$null = $soapFindEmployee.Append('<sch:EmployeeSearchInfo>')
$null = $soapFindEmployee.Append('<sch:EmployeeInfo>')
$null = $soapFindEmployee.Append("<sch:PersonnelNo>$($Account.PersonnelNo)</sch:PersonnelNo>")
$null = $soapFindEmployee.Append('</sch:EmployeeInfo>')
$null = $soapFindEmployee.Append('</sch:EmployeeSearchInfo>')
Write-Output $soapFindEmployee.ToString()
}
function Invoke-Nedap-AEOSRestMethod {
[CmdletBinding()]
param (
[string]
$Method = "POST",
[string]
$Uri = $Config.BaseUrl,
[string]
$SoapBody,
[string]
$ContentType = "text/xml; charset=UTF-8",
[System.Collections.IDictionary]
$Headers
)
process {
try {
$securePassword = $Config.Password | ConvertTo-SecureString -AsPlainText -Force
[pscredential]$credential = New-Object System.Management.Automation.PSCredential ($config.UserName, $securePassword)
[system.text.StringBuilder] $BodySB = [system.text.StringBuilder]::new()
$null = $BodySB.Append('<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sch="http://www.nedap.com/aeosws/schema">')
$null = $BodySB.Append('<soapenv:Header/>')
$null = $BodySB.Append('<soapenv:Body>')
$null = $BodySB.Append($Soapbody)
$null = $BodySB.Append('</soapenv:Body>')
$null = $BodySB.Append('</soapenv:Envelope>')
$splatParams = @{
Uri = $Uri
Method = $Method
ContentType = $ContentType
Body = $BodySB.ToString()
}
if ($Headers) {
Write-Verbose 'Adding Headers to request'
$splatParams['Headers'] = $Headers
}
if (-not [string]::IsNullOrEmpty($config.ProxyAddress)) {
$splatParams['Proxy'] = $config.ProxyAddress
}
$Response = Invoke-RestMethod @splatParams -Verbose:$false -Credential $Credential
Write-output $Response
}
catch {
$PSCmdlet.ThrowTerminatingError($_)
}
}
}
function New-SoapbodyAddEmployee {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[PSCustomObject] $Account
)
$root = "sch:EmployeeAdd"
Write-output ('<{1}>{0}</{1}>' -f $( $Account.PSObject.Properties.foreach{ if ($_.Name -ne "Id") { ' <sch:{0}>{1}</sch:{0}>' -f $_.Name, $_.Value } } -join "`n") , $root)
}
function New-SoapbodyChangeEmployee {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[PSCustomObject] $Account
)
$root = "sch:EmployeeChange"
Write-output ('<{1}>{0}</{1}>' -f $( $Account.PSObject.Properties.foreach{ ' <sch:{0}>{1}</sch:{0}>' -f $_.Name, $_.Value } -join "`n") , $root)
}
function Resolve-Nedap-AEOSError {
[CmdletBinding()]
param (
[Parameter(Mandatory)]
[object]
$ErrorObject
)
process {
$httpErrorObj = [PSCustomObject]@{
ScriptLineNumber = $ErrorObject.InvocationInfo.ScriptLineNumber
Line = $ErrorObject.InvocationInfo.Line
ErrorDetails = ''
FriendlyMessage = ''
}
$httpErrorObj.FriendlyMessage = $ErrorObject.Exception.Message
if (-not [string]::IsNullOrWhiteSpace($ErrorObject.ErrorDetails.Message)) {
$httpErrorObj.ErrorDetails = $ErrorObject.ErrorDetails.Message
}
elseif ($null -eq $ErrorObject.Exception.Response) {
$httpErrorObj.ErrorDetails = $ErrorObject.Exception.Message
}
else {
$streamReaderResponse = [System.IO.StreamReader]::new($ErrorObject.Exception.Response.GetResponseStream()).ReadToEnd()
if ( [string]::IsNullOrWhiteSpace($streamReaderResponse)) {
$httpErrorObj.ErrorDetails = $ErrorObject.Exception.Message
}
else {
$httpErrorObj.ErrorDetails = $streamReaderResponse
}
}
if ($ErrorObject.FriendlyMessage -like "*500 Internal Server Error*") {
$httpErrorObj.FriendlyMessage += " $(httpErrorObj.ErrorDetails)"
}
Write-Output $httpErrorObj
}
}
#endregion
# Begin
try {
# Verify if a user must be either [created and correlated], [updated and correlated] or just [correlated]
$Soapbody = New-SoapbodyFindEmployee -account $account
$response = Invoke-Nedap-AEOSRestMethod -SoapBody $Soapbody
$EmployeeInfo = $null;
if ($null -ne $Response.Envelope.Body) {
foreach ($Item in $Response.Envelope.Body.EmployeeList) {
if ($Item.employee.EmployeeInfo.PersonnelNo -eq $account.PersonnelNo) {
$EmployeeInfo = $Item.employee.EmployeeInfo
break
}
}
}
if (($EmployeeInfo | measure-object).count -gt 1) {
Throw "Multiple ($(($EmployeeInfo | measure-object).count)) employees with PersonnelNo [$($account.PersonnelNo)] found in AEOS"
}
if ($null -eq $EmployeeInfo) {
$action = 'Create-Correlate'
}
elseif ($updatePerson -eq $true) {
$action = 'Update-Correlate'
}
else {
$action = 'Correlate'
}
# Add a warning message showing what will happen during enforcement
if ($dryRun -eq $true) {
Write-Warning "[DryRun] $action Nedap-AEOS account for: [$($p.DisplayName)], will be executed during enforcement"
}
# Process
if (-not($dryRun -eq $true)) {
switch ($action) {
'Create-Correlate' {
Write-Verbose "Creating and correlating Nedap-AEOS account"
$Soapbody = New-SoapbodyAddEmployee -account $account
$response = Invoke-Nedap-AEOSRestMethod -SoapBody $Soapbody
$account.Id = $Response.Envelope.Body.EmployeeResult.Id
$accountReference = $account.Id
break
}
'Update-Correlate' {
Write-Verbose "Updating and correlating Nedap-AEOS account"
$account.Id = $EmployeeInfo.Id
$accountReference = $account.Id
$Soapbody = New-SoapbodyChangeEmployee -account $account
$response = Invoke-Nedap-AEOSRestMethod -SoapBody $Soapbody
break
}
'Correlate' {
Write-Verbose "Correlating Nedap-AEOS account"
$account.Id = $EmployeeInfo.Id
$accountReference = $account.Id
break
}
}
$success = $true
$auditLogs.Add([PSCustomObject]@{
Message = "$action account was successful. AccountReference is: [$accountReference]"
IsError = $false
})
}
}
catch {
$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-Nedap-AEOSError -ErrorObject $ex
$auditMessage = "Could not $action Nedap-AEOS account. Error: $($errorObj.FriendlyMessage)"
Write-Verbose "Error at Line '$($errorObj.ScriptLineNumber)': $($errorObj.Line). Error: $($errorObj.ErrorDetails)"
}
else {
$auditMessage = "Could not $action Nedap-AEOS account. Error: $($ex.Exception.Message)"
Write-Verbose "Error at Line '$($ex.InvocationInfo.ScriptLineNumber)': $($ex.InvocationInfo.Line). Error: $($ex.Exception.Message)"
}
$auditLogs.Add([PSCustomObject]@{
Message = $auditMessage
IsError = $true
})
# End
}
finally {
$result = [PSCustomObject]@{
Success = $success
AccountReference = $accountReference
Auditlogs = $auditLogs
Account = $account
#Optionally return data for use in other systems
ExportData = [PSCustomObject]@{
AEOSid = $accountReference
}
}
Write-Output $result | ConvertTo-Json -Depth 10
}