PSGraylog/Functions/Public/Connect-GraylogService.ps1

66 lines
2.7 KiB
PowerShell

function Connect-GraylogService {
<#
.SYNOPSIS
Connects to the Graylog server.
.DESCRIPTION
Connects to the Graylog server using the provided credentials.
.PARAMETER Credential
The credentials to use to connect to the Graylog server.
.OUTPUTS
None, the session is stored in the global variable $GraylogSession.
.EXAMPLE
Connect-GraylogService
Connects to the Graylog server using the stored credentials.
.EXAMPLE
Connect-GraylogService -Credential (Get-Credential)
Connects to the Graylog server using the provided credentials prompting for both the username and password.
.EXAMPLE
Connect-GraylogService -Credential (Get-Credential -UserName "ab123456")
Connects to the Graylog server using the provided credentials, prompting for just a password.
.EXAMPLE
$Credential = [PSCredential]::new("ab123456", (ConvertTo-SecureString "Password123" -AsPlainText -Force))
Connect-GraylogService -Credential $Credential
Connects to the Graylog server using the provided credentials without prompting for any input. (Other methods of creating a PSCredential object can be used)
.NOTES
The session is stored in the global variable $GraylogSession and is used for subsequent requests to the Graylog server.
#>
[Alias("Connect-Graylog")]
param (
[Parameter()]
[PSCredential]
$Credential
)
if ((Test-GraylogSession -SkipSecretCheck)) { return } # If the session is still valid, don't create a new one
if (-NOT $Credential) {
try {
$Credential = Get-Secret Graylog_Credential -Vault Graylog -ErrorAction Stop
} catch {
try {
Write-Host "The Graylog Credential secret is missing, prompting for input..."
$Credential = Get-Credential -Message "Enter your Graylog credentials (the same way as you would via the web service)"
$Credential | Set-Secret Graylog_Credential -ErrorAction Stop
} catch {
throw "Failed to set the Graylog Credential secret: $_"
}
}
}
$Request = @{
Method = "POST"
URI = "$(Get-Secret Graylog_BaseURI -Vault Graylog -AsPlainText)/api/system/sessions"
Body = ConvertTo-Json @{
host = $BaseURI.Authority
username = $Credential.Username.Split("@")[0]
password = $Credential.GetNetworkCredential().Password
}
ContentType = "application/json"
UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML; like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0"
Headers = @{ "X-Requested-By" = "XMLHttpRequest" }
SessionVariable = "GraylogSession"
}
# Use a regular Invoke-RestMethod for the initial sign-in request to avoid any issues with the WebSession
try { $null = Invoke-RestMethod @Request }
catch { throw $_.Exception.Message }
$GraylogSession | ConvertFrom-GraylogSession | Set-Secret Graylog_Session
}
# Export-ModuleMember -Function Connect-Graylog