lib/TMD.Credentials.ps1

function Add-StoredCredential {
    <#
    .SYNOPSIS
    Stores the given credential on the local hard drive

    .DESCRIPTION
    Exports the given credential object to an XML file which is saved in the TMD_Files directory

    .PARAMETER Name
    The name to be used when referencing the stored credential

    .PARAMETER Credential
    The credential object to be stored

    .PARAMETER Passthru
    Returns the PSCredential object created and stored with the Name provided

    .EXAMPLE
    Get-Credential | Add-StoredCredential -Name 'MyCreds'

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    [Alias('New-StoredCredential')]
    param(
        [CmdletBinding()]
        [Parameter(Mandatory = $true,
                   Position = 0,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('CredentialName')]
        [String]$Name,

        [Parameter(Mandatory = $false,
                   Position = 1,
                   ValueFromPipelineByPropertyName = $true)]
        [PSCredential]$Credential,

        ## Allow returning the PSCredential Object (useful when prompted for new)
        [switch]$Passthru
    )

    process {
        if (!$Credential) {
            if (Test-TMDIsRunningAction) {
                $ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
                    [Exception]::new("A Credential must be provided"),
                    "TMD.CRED01",
                    [System.Management.Automation.ErrorCategory]::InvalidArgument,
                    $null
                )
                $PSCmdlet.WriteError($ErrorRecord)
            }
            else {
                $Credential = (Get-Credential)
            }
        }
        $CredentialFilePath = Join-Path $Global:UserPaths.Credentials ($Name + '.credential')
        Export-Clixml -InputObject $Credential -Path $CredentialFilePath

        ## Return the PSCredential Object
        if($Passthru.isPresent){
            $Credential
        }
    }
}
Set-Alias -Name 'New-StoredCredential' -Value 'Add-StoredCredential' -Option AllScope -Scope Global


function Remove-StoredCredential {
    <#
    .SYNOPSIS
    Removes a previously stored credential from the local hard drive

    .DESCRIPTION
    Overwrites a stored .credential file multiple times with a random bytestream before deleting
    it from the local hard drive

    .PARAMETER Name
    The name of the credential to be removed

    .PARAMETER OverwriteCount
    The number of times to overwrite the file before removing it

    .EXAMPLE
    Remove-StoredCredential -Name 'MyCreds'

    .EXAMPLE
    Get-StoredCredential | Remove-StoredCredential

    .OUTPUTS
    None
    #>


    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true)]
        [Alias('CredentialName')]
        [ArgumentCompleter({ Get-StoredCredential -List })]
        [String]$Name,

        [Parameter(Mandatory = $false)]
        [Int]$OverwriteCount = 500
    )

    process {
        $CredentialFilePath = Join-Path -Path $Global:UserPaths.Credentials ($Name + '.credential')
        Write-Verbose "Processing file '$CredentialFilePath'"
        if (Test-Path -PathType Leaf -Path $CredentialFilePath) {
            $BufferSize = $Name.Length
            $RandomDataBuffer = [System.Byte[]]::new($BufferSize)

            Write-Verbose "Overwriting the data within the file $OverwriteCount time(s)"
            for ($i = 0; $i -lt $OverwriteCount; $i++) {
                $Random = [System.Random]::new()
                $Random.NextBytes($RandomDataBuffer) | Set-Content -Path $CredentialFilePath -AsByteStream
            }
            Write-Verbose "Removing the file"
            Remove-Item -Path $CredentialFilePath -Force
        }
        else {
            $ErrorRecord = [System.Management.Automation.ErrorRecord]::new(
                [Exception]::new("A stored credential with the name '$Name' does not exist."),
                "TMD.CRED02",
                [System.Management.Automation.ErrorCategory]::InvalidArgument,
                $CredentialFilePath
            )
            $PSCmdlet.WriteError($ErrorRecord)
        }
    }
}

function Get-StoredCredential {
    <#
    .SYNOPSIS
    Gets the specified credential that is stored on the local hard drive

    .DESCRIPTION
    This function either retrieves a specified credential or a list of all stored credentials

    .PARAMETER Name
    The name of the credential to get

    .PARAMETER List
    Switch specifying that a list of the credentials stored on the local hard drive should be returned

    .EXAMPLE
    $StoredCredential = Get-StoredCredential -Name 'MyCreds'

    .OUTPUTS
    A PSCredential object containing the specified credential
    #>


    [CmdletBinding(DefaultParameterSetName = "Single")]
    param(
        [Parameter(Mandatory = $false,
                   Position = 0,
                   ValueFromPipeline = $true,
                   ValueFromPipelineByPropertyName = $true,
                   ParameterSetName = "Single")]
        [ArgumentCompleter({ Get-StoredCredential -List })]
        [Alias('CredentialName')]
        [String]$Name,

        [Parameter(Mandatory = $false, ParameterSetName = "List")]
        [switch]$List
    )

    process{
        try {
            if (-not $Name -or $List) {
                $CredentialFolderPath = Resolve-Path $Global:UserPaths.Credentials
                $CredentialList = Get-ChildItem -Path $CredentialFolderPath -File
                $CredentialList | ForEach-Object {
                    if ($List) {
                        $_.Name -replace $_.Extension, ''
                    }
                    else {
                        [PSCustomObject]@{
                            Name = $_.Name.Replace($_.Extension, '')
                            Credential = Import-Clixml -Path $_.FullName
                        }
                    }
                }
            }
            else {
                $CredentialFilePath = Join-Path $Global:UserPaths.Credentials ($Name + '.credential')
                if (Test-Path -Path $CredentialFilePath) {
                    Import-Clixml -Path $CredentialFilePath
                }
            }
        }
        catch {
            $PSCmdlet.WriteError($_)
        }
    }
}

function Copy-StoredCredential {
    <#
    .SYNOPSIS
    Copies a stored credential

    .DESCRIPTION
    This function copies a StoredCredential from the -ExistingCredentialName to -NewCredentialName

    .PARAMETER ExistingCredentialName
    The name of the source StoredCredentail to copy

    .PARAMETER NewCredentialName
    The name of the new StoredCredential to create

    .PARAMETER Passthru
    Returns the new credential

    .EXAMPLE
    Copy-StoredCredential -ExistingCredentialName 'TMServer' -NewCredentialName 'NewTMServer'

    .EXAMPLE
    Copy-StoredCredential -ExistingCredentialName 'TMServer' -NewCredentialName 'NewTMServer' -Passthru

    .OUTPUTS
    When Passthru is used, a PSCredential is returned
    #>


    [CmdletBinding()]      # Always add CmdletBinding to expose the common Cmdlet variables
    [OutputType([Bool])]   # Add this if the function has an output
    param(
        ## TODO: Add an Argument Completer. This will require additional work on the Get- command to allow matching.
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateScript({$_ -in (Get-StoredCredential -List)})]
        [String]$ExistingCredentialName,

        [Parameter(Mandatory = $true, Position = 1)]
        [String]$NewCredentialName,

        [Switch]$Passthru
    )

    ## Get and Set the Credential
    $PSCredential = Get-StoredCredential -Name $ExistingCredentialName
    Add-StoredCredential -Name $NewCredentialName -Credential $PSCredential

    ## Return the credential if desired
    if($Passthru){
        return $PSCredential
    }


}


function Test-IsAdmin {
    <#
    .SYNOPSIS
    Checks if the current user has administrative rights

    .EXAMPLE
    $Message = Test-IsAdmin ? "User is an administrator" : "User is not an administrator"
    Write-Host $Message

    .OUTPUTS
    True if the current user is in the Administrators group, otherwise false
    #>

    [CmdletBinding()]

    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    [Security.Principal.WindowsPrincipal]::new($user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}