WhiteboardAdmin.psm1

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
Gets all of the board owners from the Microsoft Whiteboard service in a given geography.
The response is a JSON object with the following properties:
  Items:
    A list of strings containing the owner ids
  ContinuationToken:
    A continuation token to pass in future calls to this API. The token can expire when new results are computed.
    In this case a 410 is returned, and the call should be retried with a null continuation token. When this
    situation occurs, duplicate owner ids may be returned. If null, there are no more owners to return.
  Geography:
    The geography for which this results were calculated.
  TenantId:
    The tenant ID these owners belong to.
 
 
This data is not live calculated, and instead is based on cached values that are calculated
every 2-4 weeks. As a result, admins should be aware that this may be an incomplete list.
 
.PARAMETER Geography
The geography to look up whiteboards in. Valid options are "Europe", "Australia", and "Worldwide".
"Worldwide" contains all data not stored in Europe or Australia. At the time of writing, this data
is stored in the US.
 
.PARAMETER ContinuationToken
(Optional) A continuation token based on the last time this function was called. Due to the large
volume of boards in a tenant, results are returned in chunks at a time, with a continuation token
to signify where to pick up from. To start from the beginning, pass in null.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
#>

function Get-WhiteboardOwners
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateSet('Worldwide', 'Europe', 'Australia')]
        [string]$Geography,

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

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

    $response = Invoke-WhiteboardRequest `
        -Method GET `
        -Endpoint "api/v1.0/admin/whiteboardowners/geographies/$Geography" `
        -ContentType 'application/json' `
        -ForceAuthPrompt:$ForceAuthPrompt `
        -Headers @{"x-ms-continuationToken"=$ContinuationToken }

    return $response
}

<#
.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
    }
}

<#
.SYNOPSIS
Gets tenant settings from the Microsoft Whiteboard service and returns them as an object.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
Get-WhiteboardSettings
 
Get the users Whiteboard settings.
#>

function Get-WhiteboardSettings
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$false)]
        [switch]$ForceAuthPrompt)

    $response = Invoke-WhiteboardRequest `
        -Method GET `
        -Endpoint "api/v1.0/whiteboards/enabled" `
        -ForceAuthPrompt:$ForceAuthPrompt

    return $response
}

<#
.SYNOPSIS
Sets the tenant settings for the Microsoft Whiteboard services.
 
.PARAMETER Settings
The object to use as Whiteboard Settings. Should be retrieved via Get-WhiteboardSettings
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
$settings = Get-WhiteboardSettings
$settings.isEnabledGa = $true
Set-WhiteboardSettings -Settings $settings
 
Enables Microsoft Whiteboard for your tenant.
#>

function Set-WhiteboardSettings
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [psobject]$Settings,

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

    $jsonSettings = ConvertTo-Json $Settings
    $response = Invoke-WhiteboardRequest `
        -Method POST `
        -Endpoint "api/v1.0/whiteboards/enabled" `
        -ContentType 'application/json' `
        -Body $jsonSettings `
        -ForceAuthPrompt:$ForceAuthPrompt

    return $response
}


<#
.SYNOPSIS
Gets all the whiteboards associated with a tenant in a specific geography.
 
.PARAMETER Geography
The geography to grab the whiteboards from. Valide options are Australia, Europe, or Worldwide.
 
.PARAMETER ForceAuthPrompt
(Optional) Always prompt for auth. Use to ignore cached credentials.
 
.EXAMPLE
Get-WhiteboardsForTenant -Geography Europe
Gets all the whiteboards associated with the caller's tenant in Europe
#>

function Get-WhiteboardsForTenant
{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [ValidateSet('Worldwide', 'Europe', 'Australia')]
        [string]$Geography,

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

    # helper function for calling the Get-WhiteboardOwners API wrapped in a retry
    function Get-WhiteboardOwnersWithRetry(
        [Parameter(Mandatory=$true)]
        [string]$Geography,
        [Parameter(Mandatory=$false)]
        [string]$ContinuationToken) {
        $retryCount = 0
        while ($true) {
            try {
                $results = Get-WhiteboardOwners -Geography $Geography -ContinuationToken $ContinuationToken
                return $results
            } catch {
                $retryCount++
                if ($retryCount -gt 4) {
                    throw $_.Exception
                }
            }
        }
    }

    # helper function for calling the Get-Whiteboard API for a user wrapped in a retry and filtering for
    # a specific geography.
    function Get-WhiteboardsInGeographyForUser([Parameter(Mandatory=$true)][string]$OwnerId, [Parameter(Mandatory=$true)][string]$Geography) {
        $retryCount = 0
        $baseApi = ""
        if ($Geography -eq 'Worldwide') {
            $baseApi = "us*"
        }
        elseif ($Geography -eq 'Europe') {
            $baseApi = "eu*"
        }
        elseif ($geography -eq 'Australia') {
            $baseApi = "au*"
        }
        while ($true) {
            try {
                return Get-Whiteboard -UserId $ownerId | Where-Object -Property baseApi -like $baseApi
            } catch {
                $retryCount++
                if ($retryCount -gt 4) {
                    throw $_.Exception
                }
            }
        }
    }

    $continuationToken = $null
    $whiteboardsAll = @()
    do
    {
        $results = Get-WhiteboardOwnersWithRetry -Geography $Geography -ContinuationToken $continuationToken
        $continuationToken = $results.continuationToken
        foreach($ownerId in $results.items)
        {
            $whiteboards = Get-WhiteboardsInGeographyForUser -OwnerId $ownerId -Geography $Geography
            $whiteboardsAll = $whiteboardsAll + $whiteboards
        }  
    }
    while(-not [string]::IsNullOrEmpty($continuationToken))
    return $whiteboardsAll
}

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)]
    [hashtable]$Headers = $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

    if ($Headers -ne $null) {
        $Headers['Authorization'] = Get-WhiteboardAuthenticationHeader -ForceAuthPrompt:$ForceAuthPrompt
    } else {
        $Headers = @{
            'Authorization' = Get-WhiteboardAuthenticationHeader -ForceAuthPrompt:$ForceAuthPrompt
        }
    }

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

    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" }
    }
}