FastTrack-GDPR-RequestDsr.psm1

Add-Type -AssemblyName System.Web -ErrorAction SilentlyContinue

Function Get-ResponseError {
    param([System.Net.HttpWebResponse]$Response)
    $streamReader = New-Object System.IO.StreamReader($Response.GetResponseStream())
    $streamReader.BaseStream.Position = 0
    $streamReader.DiscardBufferedData()    
    $body = ConvertFrom-Json($streamReader.ReadToEnd())
    if([string]::IsNullOrEmpty($body))
    {
        $body = ConvertFrom-Json("{}")        
    }
    Add-Member -InputObject $body -MemberType NoteProperty -Name "StatusCode" -Value $_.Exception.Response.StatusCode
    $body
}
Function Invoke-GetRequest {
    param([String]$Uri, [hashtable]$Headers)
    $response = try {
        Invoke-RestMethod -Method GET -Uri $Uri -ContentType 'application/json' -Headers $Headers
    } catch {
        Get-ResponseError $_.Exception.Response
    }

    return $response
}
Function Invoke-PostRequest {
    param([String]$Uri, [hashtable]$Headers, [String]$Body)
    $response = try {
    Invoke-RestMethod -Method POST -Uri $Uri -ContentType 'application/json' -Headers $Headers -Body $Body
    } catch {
    Get-ResponseError $_.Exception.Response
    }

    return $response
}

Function SetDsrObjectValues{
    param
    (
        [string] $TenantID,
        [string] $CompanyName,
        [string] $LogonUserEmail,
        [string] $DsrRequestUserEmail,
        [string] $DsrType,
        [string] $MigrationType
    )

        $RequestUserEmails = New-Object System.Collections.Generic.List``1[System.String]

        if($DsrRequestUserEmail.Contains(","))
            {
            
                foreach($userEmail in $DsrRequestUserEmail.Split(",".ToCharArray()))
                {
                    $RequestUserEmails.Add([System.Web.HttpUtility]::HtmlEncode($userEmail));
                }
            }
        else
            {
                $RequestUserEmails.Add([System.Web.HttpUtility]::HtmlEncode($DsrRequestUserEmail));
            }

        $CustomerIdentity = (New-Object PSObject |
        Add-Member -PassThru NoteProperty TenantId $TenantID |
        Add-Member -PassThru NoteProperty CompanyName $CompanyName |
        Add-Member -PassThru NoteProperty LogOnUserEmail $LogonUserEmail)

        $CustomerObject = (New-Object PSObject |
        Add-Member -PassThru NoteProperty TransactionId ([System.Guid]::Empty) |
        Add-Member -PassThru NoteProperty DSRType $DsrType |
        Add-Member -PassThru NoteProperty Identity $CustomerIdentity |
        Add-Member -PassThru NoteProperty DsrRequestUserEmail $RequestUserEmails.ToArray() |
        Add-Member -PassThru NoteProperty EnvironmentType $global:MsoComOrGov |
        Add-Member -PassThru NoteProperty MigrationType $MigrationType)

        return $CustomerObject
}


Function Submit-FastTrackGdprDsrRequest{
<#
.SYNOPSIS
    Submit a new GDPR DSR request to remove user sensitive information from the FastTrack environment.
.DESCRIPTION
    The Submit-FastTrackGdprDsrRequest cmdlet submits a new GDPR DSR request to remove user sensitive information from the FastTrack environment.
 
    In order to use this cmdlet, you must first login using the Login-FastTrackAcount cmdlet.
 
    Once a request is submitted, you can check the status of the request use the Get-FastTrackDsrRequest cmdlet.
.PARAMETER DsrRequestUserEmail
    Email of user to remove from FastTrack
.EXAMPLE
    Submit-FastTrackGdprDsrRequest -DsrRequestUserEmail "abc@contoso.net"
.INPUTS
    System.String
.OUTPUTS
    System.Management.Automation.PSObject
        This cmdlet generates a System.Management.Automation.PSObject object that represents the Transaction ID .
.LINK
    Get-FastTrackGdprDsrRequests
    Get-FastTrackGdprDsrStatus
#>

    param
    (
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string] $DsrRequestUserEmail,
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
        [string] $EnvironmentMode = "prod"
    )

    try
    {
        $DsrType = "Delete" #defaulting value for initial release

        if($global:MsoAdminProperties.Count -eq 0)
        {
            Write-Warning "Unable to retrieve Office 365 credentials! :: Please call [Login-FastTrackAccount] function."
            return
        }
        elseif($global:MsoAdminProperties["MSO-AdminUser"] -eq $null)
        {
            Write-Warning "Logged in user is not a global admin for tenant $($global:MsoAdminProperties["MSO-CompanyInfo"].DisplayName)"
            return
        }
    
        if($global:MsoAdminProperties["MSO-AdminUser"] -ne $null)
        {
            Write-Host "Admin user validated... Preparing DSR request..."

            $jsonObj = SetDsrObjectValues -TenantID: $global:MsoAdminProperties["MSO-CompanyTenantInfo"] `
                                          -CompanyName: $global:MsoAdminProperties["MSO-CompanyInfo"].DisplayName `
                                          -LogonUserEmail: $global:MsoAdminProperties["MSO-LoggedOnUser"].Account `
                                          -DsrRequestUserEmail: $DsrRequestUserEmail `
                                          -DsrType: $DsrType

            $serializedJson = $jsonObj | ConvertTo-Json -Compress: $true
            Write-Host "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Request formatted for system request."

            $header = @{}
            $header.Add("ACCESS_TOKEN",$global:MsftAccessToken)
            $header.Add("TENANT_ID",$global:MsoAdminProperties["MSO-CompanyTenantInfo"])
            Write-Host "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Sending DSR Request."
            if($EnvironmentMode -eq "UAT")
            {
                $JsonResult = Invoke-PostRequest -Uri ([System.String]::Format("https://msft-csi-{0}.azurewebsites.net/api/DSR/Create",$EnvironmentMode)) -Headers $header -Body $serializedJson
            }
            else
            {
                $JsonResult = Invoke-PostRequest -Uri ([System.String]::Format("https://msft-cssp-{0}.azurewebsites.net/api/DSR/Create",$EnvironmentMode)) -Headers $header -Body $serializedJson
            }

            if($JsonResult.StatusCode -ne $null)
            {
                # Error?
                Write-Warning "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Request failed! : $($JsonResult.StatusCode) - Error Message: $($JsonResult)"
            }
            else
            {
                Write-Host "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Transaction Request Complete"
            }
            
            return $JsonResult | Add-Member -PassThru NoteProperty Status "Submitted"
        }
        else
        {
            Write-Warning "SORRY! - The Logon User is not marked as a Global Administrator... We cannot continue!"
        }
    }
    catch
    {
        Write-Warning -Message:"An error occurred attempting to authenticate with this module"
        Write-Warning -Message: $_.Exception.Message
        Write-Host "Press the [enter] key to close this process"
        Read-Host
    }
}

Function Get-FastTrackGdprDsrRequest {
<#
.SYNOPSIS
    Get the status of a GDPR DSR request from the FastTrack environment.
.DESCRIPTION
    The Get-FastTrackGdprDsrStatus cmdlet Get the status of a GDPR DSR request from the FastTrack environment.
 
    In order to use this cmdlet, you must first login using the Login-FastTrackAcount cmdlet.
 
    Once a request is submitted, you can check the status of the request use the Get-FastTrackDsrRequest cmdlet.
.PARAMETER TransactionId
    Unique transaction identifier
.PARAMETER EnvironmentMode
    Do not use. This parameter is for internal use.
.EXAMPLE
    Get-FastTrackGdprDsrStatus -DataServiceRequestId "RequestId"
    Get-FastTrackGdprDsrStatus
.INPUTS
    System.String
.OUTPUTS
    System.Management.Automation.PSObject
        This cmdlet generates a System.Management.Automation.PSObject object that represents FastTrack GDPR DSR status.
.LINK
    Submit-FastTrackGdprDsrRequest
    Get-FastTrackGdprDsrRequests
#>

    param
    (
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
        [string] $TransactionId,
        [Parameter(Mandatory=$false,ValueFromPipeline=$true)]
        [ValidateSet("dev","uat","prod")]
        [string] $EnvironmentMode = "prod"
    )

    try
    {
        if($global:MsoAdminProperties.Count -eq 0)
        {
            Write-Warning "Unable to retrieve Office 365 credentials! :: Please call [Login-FastTrackAccount] function."
            return
        }
    
        if($global:MsoAdminProperties["MSO-AdminUser"] -ne $null)
        {
            Write-Host "Admin user validated... Preparing DSR request..."

            [string] $TenantId = $global:MsoAdminProperties["MSO-CompanyTenantInfo"]
            [string] $query = "environmentType=$global:MsoComOrGov"

            $header = @{}
            $header.Add("ACCESS_TOKEN",$global:MsftAccessToken)
            $header.Add("TENANT_ID",$global:MsoAdminProperties["MSO-CompanyTenantInfo"])
            Write-Host "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Sending DSR Request."
            [string] $uri
            if($EnvironmentMode -eq "UAT")
            {
                #$JsonResult = Invoke-GetRequest -Uri ([System.String]::Format("https://msft-csi-{0}.azurewebsites.net/api/{1}/DSR/Status/{2}?{3}", $EnvironmentMode, $TenantId, $DataServiceRequestId, $query)) -Headers $header
                $uri = "https://msft-csi-{0}.azurewebsites.net/api"
            }
            else
            {
                #$JsonResult = Invoke-GetRequest -Uri ([System.String]::Format("https://msft-cssp-{0}.azurewebsites.net/api/{1}/DSR/Status/{2}?{3}", $EnvironmentMode, $TenantId, $DataServiceRequestId, $query)) -Headers $header
                $uri = "https://msft-cssp-{0}.azurewebsites.net/api"
            }

            if ($TransactionId -ne [string]::Empty)
            {
                $JsonResult = Invoke-GetRequest -Uri ([System.String]::Format("$uri/{1}/DSR/Status/TransactionId/{2}?{3}", $EnvironmentMode, $TenantId, $TransactionId, $query)) -Headers $header
            }
            else
            {
                $JsonResult = Invoke-GetRequest -Uri ([System.String]::Format("$uri/{1}/DSR?{2}", $EnvironmentMode, $TenantId, $query)) -Headers $header
            }

            if($JsonResult.StatusCode -ne $null)
            {
                # Error?
                Write-Warning "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Request failed! : $($JsonResult.StatusCode) - Error Message: $($JsonResult)"
            }
            else
            {
                Write-Host "[$(Get-Date -Format:'MMM-dd-yyyy HH:mm:ss')] - Transaction Request Complete"
            }
            
            return $JsonResult
        }
        else
        {
            Write-Warning "SORRY! - The Logon User is not marked as a Global Administrator... We cannot continue!"
        }
    }
    catch
    {
        Write-Warning -Message:"An error occurred attempting to authenticate with this module"
        Write-Warning -Message: $_.Exception.Message
        Write-Host "Press the [enter] key to close this process"
        Read-Host
    }
}