VMWare.Authentication.psm1

using module .\Classes\VMWare.Auth.psm1
using module .\Classes\VMWare.Settings.psm1

function New-VSphereLogin {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    [Alias('Login-VSphere')]
    param(
        [Parameter(Mandatory = $true)]
        [PSCredential]$Credential,
        [Switch]$Save,
        [String]$VSphere = ''
    )
    if ($pscmdlet.ShouldProcess('VSphere Login', 'create'))
    {
        # Choose VSphere Instance
        if ($VSphere -eq ''){
            $VSphere = Read-ValidInput -Prompt 'Enter the VSphere URL (FQDN):' -Regex '^.+\..+$'
        }

        if((Test-VSphereURL $VSphere) -eq $false){
            throw 'Failed to connect to VSphere, confirm the URL and network connectivity...'
        }

        $Auth = [VMWareAuth]::NewInstance($Credential, $VSphere)
        Write-Output "Connecting to $($Auth.VSphere)"

        if($Save){
            Save-VSphereLogin
        }
    }
}

function Save-VSphereLogin {
    [CmdletBinding()]
    param(
    )

    $Auth = [VMWareAuth]::GetInstance()
    $Auth.save()
}

function Get-VSphereLogin {
    [CmdletBinding()]
    param(
    )

    $Auth = [VMWareAuth]::GetInstance()

    return $Auth.VSphere
}

function Update-VSphere {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    param(
        [String]$VSphere
    )

    # Choose VSphere Instance
    if ($null -eq $VSphere){
        $VSphere = Read-ValidInput -Prompt 'Enter the VSphere URL (FQDN):' -Regex '^.+\..+$'
    }

    if((Test-VSphereURL $VSphere) -eq $false){
        throw 'Failed to connect to VSphere, confirm the URL and network connectivity...'
    }

    if ($pscmdlet.ShouldProcess('VSphere Login', 'update'))
    {
        $Auth = [VMWareAuth]::GetInstance()
        $Auth.UpdateVSphere($VSphere)
    }
}

<#
    .SYNOPSIS
        Tests VSphere URL for connectivity

    .DESCRIPTION
        Tests VSphere URL for connectivity on port 443 TCP

    .PARAMETER VSphere
        VSphere URL
#>

function Test-VSphereURL {
    [CmdletBinding()]
    [OutputType('System.Boolean')]
    param(
        [String]$VSphere
    )
    $result = Test-NetConnection -ComputerName $VSphere -Port 443

    if($result.TcpTestSucceeded){
        return $true
    }else{
        Write-Warning "Failed to connect to VSphere URL: $VSphere at remote address: $($result.RemoteAddress)"
        return $false
    }
}

function Test-VSphereLogin {
    [CmdletBinding()]
    param()

    $Auth = [VMWareAuth]::GetInstance()
    $Auth.ValidateLogin()
}

function Remove-VSphereLogin {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Low')]
    param(
    )
    if ($pscmdlet.ShouldProcess('VSphere Login', 'remove'))
    {
        [VMWareAuth]::ClearInstance()
        [VMWareAuth]::Delete()
    }
}