Core/ServerRake.Core.SessionManagement.ps1

############################
### SESSION MANAGEMENT ###
############################

# SECRET SERVER
function Open-SecretSession {

    [CmdletBinding(DefaultParameterSetName = 'Session')]
    param (
        
        [Parameter(ParameterSetName = 'Session')]
        [String] $ApiToken,

        [Parameter(ParameterSetName = 'Session')]
        [PSCredential] $Credential,

        [Parameter(ParameterSetName = 'Session', Mandatory = $true)]
        [String] $SecretServerURL,

        [Parameter(Mandatory = $true)]
        [String] $SecretName,

        [Parameter(ParameterSetName = 'NoSession')]
        [Switch] $NoSession

    )

    if (!$secret -AND !$secretPlain) {

        if ($NoSession) {

                $script:secret = Get-Credential -Username $SecretName
                $script:secretPlain = $secret

        } else {

            try {

                Write-Host "`nConnecting to SecretServer..."

                $baseUrl = "https://$($SecretServerURL)"

                if ($ApiToken) {

                    $script:secretServerSession = New-TssSession -SecretServer $baseUrl -AccessToken $ApiToken -ErrorAction Stop -WarningAction SilentlyContinue

                } elseif ($Credential) {

                    $script:secretServerSession = New-TssSession -SecretServer $baseUrl -Credential $Credential -ErrorAction Stop -WarningAction SilentlyContinue

                } else {

                    throw "Please provide and API Token or Credentials ('Domain\Username' and 'Password') to open a session with SecretServer."

                }
                
                Write-Host "`nConnection Successful!" -ForegroundColor Magenta
                Write-Host "Collecting Secret...`n"

                $secretId = Find-TssSecret -TssSession $secretServerSession -SecretName $SecretName -ErrorAction Stop
                $secretObject = Get-TssSecret -TssSession $secretServerSession -Id $secretId.SecretId -ErrorAction Stop
                $script:secret = $secretObject.GetCredential('domain', 'username', 'password')
                $script:secretPlain = $secretObject.GetCredential($null, 'username', 'password')

                Write-Host "`nSecret collected!" -ForegroundColor Green
                Write-Host "Use 'Close-SecretSession' to exit open Secret Server sessions when finished.`n" -ForegroundColor Yellow
            
            } catch {

                throw $_

            }

        }

    } else {
        
        Write-Host "`nThere is already an active SecretServer session." -ForegroundColor Yellow
        Write-Host "To make a new session, close the current session by running 'Close-SecretSession'.`n" -ForegroundColor Yellow

    }

}

function Close-SecretSession {

    if ($secret -AND $secretPlain) {

        try {

            if ($secretServerSession) {

                Close-TssSession -TssSession $secretServerSession -ErrorAction Stop | Out-Null
                $script:secretServerSession     =   $null

            }
            
            $script:secret                  =   $null
            $script:secretPlain             =   $null

            Write-Host "`nAny open SecretServer connection has now closed and all cached secrets have been cleared.`n" -ForegroundColor Blue

        } catch {

            Write-Host "`nAn error occured closing the SecretServer session.`n" -ForegroundColor Red
            throw $_

        }

    } else {

        Write-Host "`nNo secret session currently exists.`n" -ForegroundColor Red

    }

}

# JUMPHOSTS
function Open-DoubleHopSession {

    [CmdletBinding()]
    param (

        [Parameter(Mandatory = $True)]
        [String] $Jumphost

    )

    if (!$secret -AND !$secretPlain) {

        throw "No secret sessions are currently opened. Start a session with 'Open-SecretSession' and try again."
    
    }

    if (!$jh) {

        try {

            $script:jh = New-PSSession -ComputerName $jumphost -Credential $secretPlain -ErrorAction Stop

            Write-Host "`nDouble-hop now active. Cmdlets will now be sent to VMs via [$jumphost]." -ForegroundColor Green
            Write-Host "Use 'Close-DoubleHopSession' to exit double-hopping when finished.`n" -ForegroundColor Yellow

        } catch {

            Write-Host "`nCould not establish double-hop session.`n" -ForegroundColor Red
            throw $_

        }

    } else {

        Write-Host "`nThere is already an active Double Hop session." -ForegroundColor Yellow
        Write-Host "To start a session with a different jumphost, run 'Close-DoubleHopSession', then 'Open-DoubleHopSession'.`n" -ForegroundColor Yellow

    }

}

function Close-DoubleHopSession {

    if ($jh) {

        Remove-PSSession -Name $script:jh
        Write-Host "`nSession with jumphost is now closed.`n" -ForegroundColor Blue

        $script:jh = $null

    } else {

        Write-Host "`nNo double hop session exists.`n" -ForegroundColor Red

    }

}

# NUTANIX
function Set-NutanixCredentials {
    
    [CmdletBinding()]
    param (

        [Parameter(Mandatory = $True)]
        [String] $Username

    )

    if ($secretPlain -AND $secretPlain.Username -eq $Username) {

        $script:nxAPICreds = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($secretPlain.Username):$($secretPlain.GetNetworkCredential().Password)")) 

    } else {
        
        $credential = Get-Credential -Credential $Username
        $script:nxAPICreds = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($credential.Username):$($credential.GetNetworkCredential().Password)"))

    }

}