PSGraylog/Functions/Public/Connect-GraylogService.ps1

66 lines
2.7 KiB
PowerShell
Raw Normal View History

2024-07-25 02:31:34 +01:00
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
2024-07-25 02:31:34 +01:00
if (-NOT $Credential) {
try {
$Credential = Get-Secret Graylog_Credential -Vault Graylog -ErrorAction Stop
2024-07-25 02:31:34 +01:00
} 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"
2024-07-25 02:31:34 +01:00
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 }
2024-07-25 02:31:34 +01:00
$GraylogSession | ConvertFrom-GraylogSession | Set-Secret Graylog_Session
}
# Export-ModuleMember -Function Connect-Graylog