WhiteboardAdmin.psm1

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
Set-Variable AdalClientId -option Constant -value '1950a258-227b-4e31-a9cf-717495945fc2'
Set-Variable AdalRedirectUri -option Constant -value 'https://login.microsoftonline.com/common/oauth2/nativeclient'

<#
.SYNOPSIS
Gets one or more Whiteboards from the Microsoft Whiteboard service and returns them as objects.
 
.PARAMETER UserId
The ID of the user account to query Whiteboards for.
 
.PARAMETER WhiteboardId
(Optional) The ID of a specific Whiteboard to query, if not specified all whiteboards are queried.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
Get-Whiteboard -UserId 00000000-0000-0000-0000-000000000001
Get all of a user's Whiteboards.
#>

function Get-Whiteboard
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [Guid]$UserId,

        [Parameter(Mandatory=$false)]
        [Guid]$WhiteboardId,

        [Parameter(Mandatory=$false)]
        [switch]$ForceAuthPrompt)

    $response = Invoke-WhiteboardRequest `
        -Method GET `
        -Endpoint "api/v1.0/users/$UserId/whiteboards" `
        -ContentType 'application/json' `
        -ForceAuthPrompt:$ForceAuthPrompt

    if ($null -eq $WhiteboardId)
    {
        return $response
    }

    # Filter client-side since there is no admin GET API that addresses a single whiteboard.
    return $response | Where-Object {$_.id -eq $WhiteboardId}
}

<#
.SYNOPSIS
Sets the owner for a Whiteboard.
 
.PARAMETER WhiteboardId
The Whiteboard for which the owner is being changed.
 
.PARAMETER OldOwnerId
The ID of the previous owner.
 
.PARAMETER NewOwnerId
The ID of the new owner.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
Set-WhiteboardOwner -OldOwnerId 00000000-0000-0000-0000-000000000001 -NewOwnerId 00000000-0000-0000-0000-000000000002
Move a Whiteboard from one user to another.
#>

function Set-WhiteboardOwner
{
    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact='High')]
    param(
        [Parameter(Mandatory=$true)]
        [Guid]$WhiteboardId,

        [Parameter(Mandatory=$true)]
        [Guid]$OldOwnerId,

        [Parameter(Mandatory=$true)]
        [Guid]$NewOwnerId,

        [Parameter(Mandatory=$false)]
        [switch]$ForceAuthPrompt)

    if ($PSCmdlet.ShouldProcess("Whiteboard: $WhiteboardId"))
    {
        return Invoke-WhiteboardRequest `
            -Method PATCH `
            -Endpoint "api/v1.0/users/$OldOwnerId/whiteboards/$WhiteboardId" `
            -ContentType 'application/json-patch+json' `
            -Body (ConvertTo-Json -Compress @(@{"op"="replace"; "path"="/OwnerId"; "value"=$NewOwnerId })) `
            -ForceAuthPrompt:$ForceAuthPrompt
    }
}

<#
.SYNOPSIS
Transfer ownership of all Whiteboards owned by a user to another user.
 
.PARAMETER OldOwnerId
The ID of the previous owner.
 
.PARAMETER NewOwnerId
The ID of the new owner.
 
.PARAMETER WhatIf
Execute the command without making any actual changes. Only calls read methods on the REST service.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
Invoke-TransferAllWhiteboards -OldOwnerId 00000000-0000-0000-0000-000000000001 -NewOwnerId 00000000-0000-0000-0000-000000000002 -WhatIf
Check how many Whiteboards will be transferred without transferring them.
 
.EXAMPLE
Invoke-TransferAllWhiteboards -OldOwnerId 00000000-0000-0000-0000-000000000001 -NewOwnerId 00000000-0000-0000-0000-000000000002
Transfer (and prompt before performing any write actions).
#>

function Invoke-TransferAllWhiteboards
{
    [CmdletBinding(
        SupportsShouldProcess = $true,
        ConfirmImpact='High')]
    param(
        [Parameter(Mandatory=$true)]
        [Guid]$OldOwnerId,

        [Parameter(Mandatory=$true)]
        [Guid]$NewOwnerId,

        [Parameter(Mandatory=$false)]
        [switch]$ForceAuthPrompt)

    $whiteboards = Get-Whiteboard -UserId $OldOwnerId -ForceAuthPrompt:$ForceAuthPrompt

    # Only transfer Whiteboards actually owned by this Id
    $whiteboardsOwned = @($whiteboards | Where-Object { [Guid]::Parse($_.ownerId) -eq $OldOwnerId })
    Write-Verbose "Found $($whiteboardsOwned.Length) Whiteboards for owner $($OldOwnerId)"

    if ($PSCmdlet.ShouldProcess("Whiteboards for Owner: $OldOwnerId"))
    {
        $whiteboardsOwned | ForEach-Object {
            Set-WhiteboardOwner -OldOwnerId $OldOwnerId -NewOwnerId $NewOwnerId -WhiteboardId $_.id -Confirm:$false
        }
    }
}

<#
.SYNOPSIS
Deletes the specified Whiteboard for the given user from the Microsoft Whiteboard service. If the user is the owner of the whiteboard,
the entire whiteboard will be deleted. If the user has joined the whiteboard but does not own it, they will be removed and the whiteboard
will still be accessible by others.
 
.PARAMETER UserId
The ID of the user account to delete the Whiteboard from.
 
.PARAMETER WhiteboardId
The ID of a specific Whiteboard to delete.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
Remove-Whiteboard -UserId 00000000-0000-0000-0000-000000000001 -WhiteboardId 00000000-0000-0000-0000-000000000002
Deletes the whiteboard
#>

function Remove-Whiteboard
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [Guid]$UserId,

        [Parameter(Mandatory=$true)]
        [Guid]$WhiteboardId,

        [Parameter(Mandatory=$false)]
        [switch]$ForceAuthPrompt)
        
    if ($PSCmdlet.ShouldProcess("Delete whiteboard $WhiteboardId for User $UserId?"))
    {
        Invoke-WhiteboardRequest `
            -Method DELETE `
            -Endpoint "api/v1.0/users/$UserId/whiteboards/$WhiteboardId" `
            -ContentType 'application/json' `
            -ForceAuthPrompt:$ForceAuthPrompt
    }
}

function Invoke-WhiteboardRequest(
    [Parameter(Mandatory=$true)]
    [Microsoft.PowerShell.Commands.WebRequestMethod]$Method,

    [Parameter(Mandatory=$true)]
    [string]$Endpoint,

    [Parameter(Mandatory=$false)]
    [string]$ContentType = $null,

    [Parameter(Mandatory=$false)]
    [string]$Body = $null,

    [Parameter(Mandatory=$false)]
    [switch]$ForceAuthPrompt)
{
    # Make sure TLS 1.2 is a supported protocol since this is all the whiteboard service supports.
    [Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol, [Net.SecurityProtocolType]::Tls12

    $invokeRestMethodArgs = @{
        Method = $Method
        Uri = "https://$(Get-WhiteboardHostName -Environment $env:Environment)/$Endpoint"
        ContentType = $ContentType
        UserAgent = "WhiteboardAdminModule/$((Get-Module WhiteboardAdmin | Select-Object -First 1).Version)"
        Headers = @{
            'Authorization' = Get-WhiteboardAuthenticationHeader -ForceAuthPrompt:$ForceAuthPrompt
        }
    }

    if (-Not [string]::IsNullOrEmpty($Body))
    {
        $invokeRestMethodArgs["Body"] = $Body
    }

    try
    {
        return Invoke-RestMethod @invokeRestMethodArgs
    }
    catch [System.Net.WebException]
    {
        $ex = $_.Exception
        if ($ex.Status -ne [System.Net.WebExceptionStatus]::ProtocolError)
        {
            # Rethrow the exception if the failure wasn't caused by a protocol error.
            throw $ex
        }

        $response = $ex.Response
        if ($response.StatusCode -ne [System.Net.HttpStatusCode]::Unauthorized)
        {
            # Rethrow the exception if the failure wasn't caused by a unauthroized response
            throw $ex
        }

        # Try to deserialize the adal claims challenge.
        # This can happen if the endpoint makes an onbehalf
        # of request that requires additional claims (like MFA)
        try
        {
            $stream = $response.GetResponseStream()
            $streamReader = [System.IO.StreamReader]::new($stream)
            $content = $streamReader.ReadToEnd()
            $claims = ($content | ConvertFrom-Json).claims

            if ([string]::IsNullOrEmpty($claims))
            {
                throw $ex
            }
        }
        catch
        {
            throw $ex
        }

        $invokeRestMethodArgs['Headers']['Authorization'] = Get-WhiteboardAuthenticationHeader -Claims $claims -ForceAuthPrompt:$ForceAuthPrompt

        return Invoke-RestMethod @invokeRestMethodArgs
    }
}

function Get-WhiteboardAuthenticationHeader(
    [Parameter(Mandatory=$false)]
    [string]$Claims,

    [Parameter(Mandatory=$false)]
    [switch]$ForceAuthPrompt)
{
    $whiteboardResourceId = Get-WhiteboardResourceId -Environment $env:Environment
    $aadAuthority = Get-AadAuthority -Environment $env:Environment

    $authContext = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext]::new($aadAuthority)
    $promptBehavior = if ($ForceAuthPrompt -eq $true) { [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Always } else { [Microsoft.IdentityModel.Clients.ActiveDirectory.PromptBehavior]::Auto }
    $platformParameters = [Microsoft.IdentityModel.Clients.ActiveDirectory.PlatformParameters]::new($promptBehavior)
    $userIdentifier = [Microsoft.IdentityModel.Clients.ActiveDirectory.UserIdentifier]::AnyUser

    if (-Not ([string]::IsNullOrEmpty($Claims)))
    {
        $adalQueryString = "claims=$Claims"
    }

    $result = $authContext.AcquireTokenAsync($whiteboardResourceId, $AdalClientId, $AdalRedirectUri, $platformParameters, $userIdentifier, $adalQueryString).Result

    return $result.CreateAuthorizationHeader();
}

function Get-WhiteboardHostName(
    [Parameter(Mandatory=$false)]
    [ValidateSet('Prod', 'Int', 'Dev', '')]
    [string] $Environment)
{
    switch ($Environment)
    {
        'Dev'   { return "dev.whiteboard.microsoft.com"}
        'Int'   { return "int.whiteboard.microsoft.com"}
        default { return  "whiteboard.microsoft.com" }
    }
}

function Get-WhiteboardResourceId(
    [Parameter(Mandatory=$false)]
    [ValidateSet('Prod', 'Int', 'Dev', '')]
    [string] $Environment)
{
    switch ($Environment)
    {
        'Int'   { return "https://int.whiteboard.microsoft.com"}
        default { return  "https://whiteboard.microsoft.com" }
    }
}

function Get-AadAuthority(
    [Parameter(Mandatory=$false)]
    [ValidateSet('Prod', 'Int', 'Dev', '')]
    [string] $Environment)
{
    switch ($Environment)
    {
        'Int'   { return "https://login.windows-ppe.net/common"}
        default { return "https://login.microsoftonline.com/common" }
    }
}