Files
ps.ipam/functions/public/New-Session.ps1
2022-12-17 14:36:41 +03:00

111 lines
3.3 KiB
PowerShell

function New-Session {
<#
.SYNOPSIS
Creates new session to phpIPAM instance.
.DESCRIPTION
Creates new session to phpIPAM instance by provided credentials or token.
.PARAMETER URL
Base URL of phpIPAM instance.
Example - http://ipam.example.com
.PARAMETER AppID
API id (specified in phpIPAM api settings)
.PARAMETER Token
User token foor authorization
.PARAMETER IgnoreSSL
Ignore SSL errors
.OUTPUTS
None. New-Session does not generate any output.
#>
[CmdletBinding(DefaultParameterSetName="Credentials")]
param (
[parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0
)]
[ValidateNotNullOrEmpty()]
[validatescript({$_.startswith("http")})]
[string]$URL,
[parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=1
)]
[ValidateNotNullOrEmpty()]
[string]$AppID,
[parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=2,
ParameterSetName="Credentials"
)]
[ValidateNotNullOrEmpty()]
[pscredential]$Credentials,
[parameter(
Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=2,
ParameterSetName="Token"
)]
[ValidateNotNullOrEmpty()]
[string]$Token,
[parameter(
Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=3
)]
[switch]$IgnoreSSL = $false
)
switch ($PSCmdlet.ParameterSetName) {
"Credentials" {
$_bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($Credentials.Password)
$_password = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($_bstr)
$_uri = "$URL/api/$AppID/user"
$_auth = [System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes("$($Credentials.UserName):$_password"))
$_headers = @{
"Accept" = "application/json"
"Content-Type" = "application/json"
"Authorization" = "Basic $_auth"
}
$_response = Invoke-RestMethod -Method POST -Uri $_uri -Headers $_headers
if ($_response.success -ne $true) { return $_response.error }
$script:psipamSession = [PS.IPAM.Session]::new(
[ps.ipam.authType]::credentials,
$_response.data.token,
$AppID,
$URL,
(Get-Date $_response.data.expires),
$Credentials
)
break
}
"Token" {
$script:psipamSession = [PS.IPAM.Session]::new(
[ps.ipam.authType]::token,
$Token,
$AppID,
$URL,
$null,
$null
)
break
}
}
}
Export-ModuleMember -Function New-Session