Functions/Connection/Connect-CdsUser.ps1

<#
    .SYNOPSIS
    Authenticate user to discovery service
#>

function Connect-CdsUser {
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory=$false)]
        [String]
        $UserName,

        [Parameter(Mandatory=$false)]
        [String]
        $Password,        

        [Parameter(Mandatory = $true)]
        # TODO : Check AD and IFD
        [ValidateSet("Office365", "AD", "Ifd")]
        [string]
        $AuthType,
        
        [Parameter(Mandatory = $false)]
        [String]
        [ArgumentCompleter( { Get-CdsRegions })]
        $Region
    )
    begin {   
        $StopWatch = [System.Diagnostics.Stopwatch]::StartNew(); 
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Start -Parameters ($MyInvocation.MyCommand.Parameters);        
    }    
    process {   

        # Set Credential object required authentications
        $credentials = Set-CdsCredentials -Login $UserName -Password $Password;        
                
        # Initialize context
        $Global:CdsContext = New-CdsContext; 

        $cdsConnection = New-CdsConnection;   
        $cdsConnection.AuthType = $AuthType;
        $cdsConnection.UserName = $UserName;
        $cdsConnection.Password = $Password;
        $cdsConnection.Credentials = $credentials;
        $cdsConnection.Region = $Region;

        $Global:CdsContext.IsOnline = ($AuthType -eq "Office365");
        $Global:CdsContext.IsOnPremise = ($AuthType -eq "Office365");

        $Global:CdsContext.CurrentConnection = $cdsConnection;
        $Global:CdsContext.IsUserConnected = $true;
    }
    end {
        $StopWatch.Stop();
        Trace-CdsFunction -Name $MyInvocation.MyCommand.Name -Stage Stop -StopWatch $StopWatch;
    }    
}

Export-ModuleMember -Function Connect-CdsUser -Alias *;