Public/Send-ADUsersToBB.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
369
370
371
Function Send-ADUsersToBB {
    <#
    .SYNOPSIS
        Get the user information from the pipeline that is already converted to a GoBright object, and send it to the GoBright system
    .DESCRIPTION
        The pipeline should contain the converted user information
    .PARAMETER BrightBookingApiUrl
        Address of the GoBright API, e.g.: https://t1b.gobright.cloud/ (please get this from the 'General Settings' page of the portal)
    .PARAMETER BrightBookingApiKey
        API key of the user to use to process the import
    .PARAMETER BrightBookingIntegrationName
        Name of the integration to link the users to
    .PARAMETER UserRoleNameForNewUsers
        Name of the GoBright userrole to link new users to
    .PARAMETER DeactivateExistingUsersInSameIntegrationThatAreNotLoaded
        Deactivate users that exist in the platform in the same integration but are not loaded anymore from AD (e.g. because they are not anymore in the group you filter on)
    .PARAMETER ProcessingModeToPlatform
        By default the command will wait until the synchronization is processed by the platform and the result is known, and the result will be shown.
        Use the value "FireAndForget" if you want to fire the contents to the platform and not want to wait for the result. Please note that because of throttling you still have to wait untill the processing is finished and the new set is allowed before you can start a new synchronization
    .EXAMPLE
        Get-ADUsersForBB -Filter * | Convert-ADUsersToBBUserExport | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get all users in the Active Directory and let GoBright process it directly
    .EXAMPLE
        Get-ADUsersForBB -Filter * -SearchBase "OU=Office,DC=Company,DC=com" | Convert-ADUsersToBBUserExport | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which are member of the given group and let GoBright process it directly
    .EXAMPLE
        Get-ADUsersForBB -Filter { memberOf -RecursiveMatch "CN=Administrators,DC=Company,DC=com" } -SearchBase "OU=Office,DC=Company,DC=com" | Convert-ADUsersToBBUserExport -ADUserPincodePropertyName PersonnelNumber | Send-ADUsersToBB -BrightBookingApiUrl "https://eu1.api.brightbooking.eu/" -BrightBookingApiKey "[your api key]" -BrightBookingIntegrationName "Office 365"
        # Get the users in the Active Directory, which in the specified SearchBase path, and use the custom property 'PersonnelNumber' as pincode and let GoBright process it directly
    .LINK
        https://support.gobright.com/
    #>


    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $True, ValueFromPipeline = $True)]
        [System.Object[]]$pipelineConvertedADUsers,

        [Parameter(Mandatory = $True)]
        [string]$BrightBookingApiUrl,

        [Parameter(Mandatory = $True)]
        [string]$BrightBookingApiKey,

        [Parameter(Mandatory = $True)]
        [string]$BrightBookingIntegrationName,

        [Parameter(Mandatory = $False)]
        [string]$UserRoleNameForNewUsers,

        [Parameter(Mandatory = $False)]
        [bool]$SyncIncludesUserNFCId,

        [Parameter(Mandatory = $False)]
        [bool]$SyncIncludesUserPincode,

        [switch]$DeactivateExistingUsersInSameIntegrationThatAreNotLoaded
    )

    Begin {
        $convertedUsers = @()
    }

    Process {
        Foreach ($user in $pipelineConvertedADUsers) {
            $convertedUsers += $user
        }
    }

    End {
        Write-Output ""
        $countConvertedUsers = $convertedUsers | Measure-Object | Select-Object -ExpandProperty Count;
        Write-Output "Will process $countConvertedUsers users from retreived data..."

        Write-Output ""
        Write-Output "Connecting to the GoBright API..."
        Write-Output ""

        # get an access token
        $access_token = Get-BBAccessToken -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiKey $BrightBookingApiKey

        # check if we can start a new session at all
        $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $false -ValidateCanStartNew $true

        # get the user roles from the API
        $userroles = Get-BBUserRole -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token

        If ($DeactivateExistingUsersInSameIntegrationThatAreNotLoaded.IsPresent -eq $True) {
            # get active users to compare
            $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/synchronize-get-data")

            $GetQueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
            $GetQueryParameters['integrationname'] = $BrightBookingIntegrationName

            $GetRequest = [System.UriBuilder]($resturi)
            $GetRequest.Query = $GetQueryParameters.ToString()

            $GetHdrs = @{}
            $GetHdrs.Add("Authorization", "Bearer " + $access_token)

            $usersViewForSync = $null
            Try {
                Write-Output "Getting comparison data (this might take a while)..."
                $response = Invoke-WebRequest -TimeoutSec 1200 -Uri $GetRequest.Uri -Method Get -Headers $GetHdrs -UseBasicParsing

                If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201) {
                    $usersViewForSync = ConvertFrom-Json $([String]::new($response.Content))
                    # will proceed below...
                }
                Else {
                    throw "Could not get comparison data, unexpected statuscode $response.StatusCode"
                }
            }
            Catch {
                $statusCode = $_.Exception.Response.StatusCode.Value__
                $responseText = $_.ErrorDetails.Message

                Try {
                    If ($responseText) {
                        $jsonresponse = $responseText | ConvertFrom-Json
                        If ($jsonresponse.SyncRoot) {
                            $statusMessage = $jsonresponse.SyncRoot | Select-Object * | Format-List | Out-String
                        }
                        Else {
                            $statusMessage = $responseText
                        }
                    }
                }
                Catch {
                    $statusMessage = $responseText
                }

                Write-Warning "Could not get comparison data"
                Write-Warning "Statuscode: $statusCode"
                If ($statusMessage) {
                    Write-Warning "Statusdetails:"
                    $statusMessage = $statusMessage.Trim()
                    Write-Warning $statusMessage
                }

                throw "Could not get comparison data"
            }

            ##
            # process comparison
            Write-Output "Comparing..."

            If ($usersViewForSync) {
                If ($usersViewForSync.ActiveUsersInIntegration) {
                    $amountToBeDeactivated = 0;
                    # compare to get the users which are now not in the resultset from AD, and are still active in the platform -> so must be disabled
                    Foreach ($activeUserInIntegration in $usersViewForSync.ActiveUsersInIntegration) {
                        $activeUserInIntegrationFound = $false;
                        # exists this one in the $convertedUsers?
                        Foreach ($convertedUser in $convertedUsers) {
                            $found = ((-Not [string]::IsNullOrEmpty($convertedUser.UniqueImportID)) -And ($convertedUser.UniqueImportID -ceq $activeUserInIntegration.UUI)) -Or ((-Not [string]::IsNullOrEmpty($convertedUser.EmailAddress)) -And ($convertedUser.EmailAddress -eq $activeUserInIntegration.EA));

                            If ($found) {
                                $activeUserInIntegrationFound = $true;
                                Break;
                            }
                        }

                        If (-Not $activeUserInIntegrationFound) {
                            # should be disabled
                            $outputUserPropertiesHash = [ordered]@{
                                EmailAddress   = $activeUserInIntegration.EA
                                UniqueImportID = $activeUserInIntegration.UII
                                Active         = $false
                            }

                            $outputUser = New-Object PSObject -Property $outputUserPropertiesHash
                            $convertedUsers += $outputUser

                            $amountToBeDeactivated++;
                        }
                    }

                    Write-Output "Will deactivate $amountToBeDeactivated users..."
                }
            }
        }
        Else {
            Write-Output "Skipping checking for deactivation of users that exist in the platform but are not loaded anymore from AD (e.g. because they are not anymore in the group you filter on). Please use the -DeactivateExistingUsersInSameIntegrationThatAreNotLoaded switch parameter to enable deactivation checking."
        }
        Write-Output ""

        # do additional preprocessing for users
        $preprocessedUsers = @()
        Foreach ($convertedUser in $convertedUsers) {
            # translate the mapped roles, and remove the property (because it should not be tranfered to the CSV, only the translated value should)
            $mappedUserroleIds = @()
            If ($convertedUser.UserMappedRoles) {
                Foreach ($convertedUserMappedRole in $convertedUser.UserMappedRoles) {
                    $filterProductType = 0
                    If ($convertedUserMappedRole.RoleType) {
                        If ($convertedUserMappedRole.RoleType -eq "View") {
                            $filterProductType = 1
                        } Else {
                            $filterProductType = 0
                        }
                    }

                    # map to an userroleid
                    # search in the userdefined roles
                    $userroleId = ($userroles | Where-Object { $_.IsUserDefined -and ($_.Name -eq $convertedUserMappedRole.RoleName) -and ($_.Product -eq $filterProductType) } | Select-Object Id).Id;

                    If (-not $userroleId) {
                        # if not found, search all roles
                        $userroleId = ($userroles | Where-Object { ($_.Name -eq $convertedUserMappedRole.RoleName) -and ($_.Product -eq $filterProductType) } | Select-Object Id).Id;
                    }

                    If ($userroleId) {
                        # only add if not already in, nobody like duplicates
                        If (-not ($mappedUserroleIds -contains $userroleId)) {
                            $mappedUserroleIds += $userroleId
                        }
                    }
                    Else {
                        Write-Error " - Role '$($convertedUserMappedRole.RoleName)' not found via API, user $($convertedUser.EmailAddress) cannot be mapped correctly, check the names of the roles in the mapping, they probably do not match the role names in the portal"
                    }
                }
            }
            # remove the UserMappedRoles property
            $convertedUser = $convertedUser | Select-Object -Property * -ExcludeProperty UserMappedRoles
            # add the RoleIds property
            $mappedUserroleIdsAsString = $mappedUserroleIds -join ","
            $convertedUser | Add-Member RoleIdsOrNames $mappedUserroleIdsAsString -Force

            $preprocessedUsers += $convertedUser
        }

        # generate the csv file contents, generate to string
        $csvtext = $preprocessedUsers | ConvertTo-Csv -NoTypeInformation | Out-String

        # post stuff to the api
        $resturi = [System.Uri]::new([System.Uri]::new($BrightBookingApiUrl), "/api/users/batch-import-csv/schedule")

        $QueryParameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
        $QueryParameters['integrationname'] = $BrightBookingIntegrationName
        $QueryParameters['userrolename'] = $UserRoleNameForNewUsers
        $QueryParameters['import_structure_version'] = 2

        If ($SyncIncludesUserPincode) {
            Write-Output "Sync does include user pincodes..."
            $QueryParameters['syncincludesuserpincode'] = "true"
        }
        Else {
            $QueryParameters['syncincludesuserpincode'] = "false"
        }

        If ($SyncIncludesUserNFCId) {
            Write-Output "Sync does include user NFC ids..."
            $QueryParameters['syncincludesusernfcid'] = "true"
        }
        Else {
            $QueryParameters['syncincludesusernfcid'] = "false"
        }

        $Request = [System.UriBuilder]($resturi)
        $Request.Query = $QueryParameters.ToString()

        # convert the text so the encoding is correct to handle special characters
        $body = [System.Text.Encoding]::UTF8.GetBytes($csvtext)

        $hdrs = @{}
        $hdrs.Add("Authorization", "Bearer " + $access_token)

        Try {
            Write-Output ""
            Write-Output "Starting processing users in GoBright..."
            Write-Output ""

            $response = Invoke-WebRequest -TimeoutSec 1200 -Uri $Request.Uri -Method Post -Body $body -ContentType 'application/text' -Headers $hdrs -UseBasicParsing

            If ($response.StatusCode -eq 200 -or $response.StatusCode -eq 201) {
                Write-Output "Succesfully started user synchronization to GoBright, we will now wait for the result (this will take a while)"
                Write-Output ""
                Write-Output "Processing..."

                # wait for processing finished
                $keepprocessing = $true
                $waitseconds = 30
                $totalwaitedseconds = 0
                While ($keepprocessing) {
                    Start-Sleep -Seconds $waitseconds
                    $totalwaitedseconds = $totalwaitedseconds + $waitseconds

                    $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $false
                    If ($status.IsCurrentlyProcessing) {
                        Write-Output "Processing..."

                        If ($waitseconds -lt 60) {
                            $waitseconds = $waitseconds + 5;
                        }
                    }
                    Else {
                        # finished processing
                        Break
                    }
                }

                Write-Output "Processing..."
                Write-Output ""
                # sleep another 32 seconds to overcome the 30 sec limit that is neccessary to do a next call to satisfy the 30sec window (doing 2 sec extra for clockskew)
                Start-Sleep -Seconds 32

                # get the result status
                $status = Get-BBUserSyncStatus -BrightBookingApiUrl $BrightBookingApiUrl -BrightBookingApiToken $access_token -IncludeLastSyncResult $true

                If ($status.LastResult.Succeeded) {
                    Write-Output "Finished synchronizing users to GoBright successfully"
                }
                Else {
                    Write-Error "Synchronizing users to GoBright failed"
                }
                Write-Output "Results:"
                Write-Output $(' Succeeded : {0}' -f $status.LastResult.Succeeded)
                Write-Output $(' Created : {0}' -f $status.LastResult.AmountCreated)
                Write-Output $(' Updated : {0}' -f $status.LastResult.AmountUpdated)
                Write-Output $(' Not needed to process : {0} (already up to date, or because duplicate)' -f $status.LastResult.AmountExcludedInPreProcessing)
                Write-Output $(' Ignored : {0} (because invalid)' -f $status.LastResult.AmountIgnored)
                Foreach ($ignoredUser in $status.LastResult.IgnoredUsers) {
                    Write-Output $(' - Ignored user: {0}' -f $ignoredUser.Identifier)
                    Write-Output $(' - Validation errors:')
                    Foreach ($validationError in $ignoredUser.ValidationErrors) {
                        Write-Output $(' -> Property: {0}' -f $validationError.Property)
                        Write-Output $(' -> ErrorCode: {0}' -f $validationError.ErrorCode)
                        Write-Output $(' -> Value: {0}' -f $validationError.Value)
                    }
                }

                If ((-not $status.LastResult.Succeeded) -or ($status.LastResult.AmountIgnored -gt 0)) {
                    Throw "Processing the synchronization failed."
                }
            }
            Else {
                Write-Output "Could not start synchronization of users to GoBright , unexpected statuscode $response.StatusCode"
            }
        }
        Catch {
            $statusCode = $_.Exception.Response.StatusCode.Value__
            $responseText = $_.ErrorDetails.Message

            Try {
                If ($responseText) {
                    $jsonresponse = $responseText | ConvertFrom-Json
                    If ($jsonresponse.SyncRoot) {
                        $statusMessage = $jsonresponse.SyncRoot | Select-Object * | Format-List | Out-String
                    }
                    Else {
                        $statusMessage = $responseText
                    }
                }
            }
            Catch {
                $statusMessage = $responseText
            }

            Write-Warning "Synchronizing users to GoBright failed, please check the user data you have selected from your AD"
            Write-Warning "Statuscode: $statusCode"
            If ($statusMessage) {
                Write-Warning "Statusdetails:"
                $statusMessage = $statusMessage.Trim()
                Write-Warning $statusMessage
            }

            Throw "Synchronizing users failed"
        }
    }
}