Skip to content

Commit

Permalink
Redesign Items and use OpenAPi Datafile
Browse files Browse the repository at this point in the history
  • Loading branch information
fvanroie committed May 23, 2018
1 parent 78f7459 commit 47900c0
Show file tree
Hide file tree
Showing 9 changed files with 10,375 additions and 119 deletions.
10,148 changes: 10,148 additions & 0 deletions Data/opnsense.json

Large diffs are not rendered by default.

11 changes: 9 additions & 2 deletions PS_OPNsense.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
$IsPSCoreEdition = ($PSVersionTable.PSEdition -eq 'Core')
$minversion = [System.Version]'18.1.7'


$debug = $true

# Load individual functions from scriptfiles
# TODO : itterate over the objectmap and test if all Objects can be instantiated
Expand Down Expand Up @@ -71,6 +71,13 @@ ForEach ($Folder in 'Classes') {
# Load external data files
# TODO : convert this to a ps1 file so it can be code-signed
Try {
if ($debug) {
Write-Host -ForegroundColor Gray "ScriptRoot: $PSScriptRoot"
}
# Load objectmap of api calls
$FullPath = ("{0}/{1}" -f $PSScriptRoot, 'Data/opnsense.json')
$OPNsenseOpenApi = Import-OpenApiData $FullPath

# Load objectmap of api calls
$FullPath = ("{0}/{1}" -f $PSScriptRoot, 'Data/items.json')
$OPNsenseItemMap = Get-Content $FullPath | ConvertFrom-Json
Expand Down Expand Up @@ -104,7 +111,7 @@ $f = @(########## PLUGINS ##########

########## CORE ##########
# RestApi
'Invoke-OPNsenseCommand',
'Invoke-OPNsenseCommand', 'Invoke-OPNsenseApiCommand',
# Firmware
'Get-OPNsense', 'Set-OPNsense',

Expand Down
53 changes: 53 additions & 0 deletions Private/Import-OpenApiData.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
Function Import-OpenApiData {
param (
[String]$FilePath
)
$OpenApiData = Get-Content -Path $FilePath | ConvertFrom-Json
$OpenApiHash = @{}
foreach ($path in $OpenApiData.paths.psobject.properties) {
$Module = $path.name.split('/')[1]

foreach ($prop in $path.value.PSObject.properties) {
if ($prop.value.operationId) {
if ($prop.value.operationId -match "(.*?)$Module(.*)") {

$Action = $matches[1]
$Object = $matches[2]

if (-Not $OpenApiHash.containskey($Module)) {
$OpenApiHash.Add($module, @{})
}
if (-Not $OpenApiHash.$Module.containskey($Action)) {
$OpenApiHash.$Module.Add($Action, @{})
}
if (-Not $OpenApiHash.$Module.$Action.containskey($Object)) {
$OpenApiHash.$Module.$Action.Add($Object, @{})
}

$NamespaceIn = $prop.value.requestBody.content.'application/json'.schema.'$ref'
$NamespaceOut = $prop.value.responses.'200'.content.'application/json'.schema.'$ref'

# Find parameter objects from the schema based on the schema name in the path
$parameters = $OPNsenseOpenApi.components.parameters.psobject.Properties |
Where-Object { ( '#/components/parameters/{0}' -f $_.Name) -in $prop.value.parameters.'$ref' }

$OpenApiHash.$Module.$Action.$Object =
[PSCustomObject]@{
# Module = $Module
# Action = $Action
# Object = $Object
Method = $Prop.name
Path = $Path.Name
Parameters = $Parameters
NameSpaceIn = $NamespaceIn
NamespoaceOut = $NamespaceOut
}

} else {
#Write-Warning $prop.name
}
}
}
}
return $OpenApiHash
}
25 changes: 14 additions & 11 deletions Private/Invoke-OPNsenseApiRestCommand.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ Function Invoke-OPNsenseApiRestCommand {
[PSCredential]$Credential,
$Json,
$Form,
$Method,
[System.IO.FileInfo]$OutFile,
[Switch]$SkipCertificateCheck = $false
)
Expand Down Expand Up @@ -71,39 +72,42 @@ Function Invoke-OPNsenseApiRestCommand {
} elseif ($Json.GetType().Name -eq "String") {
# ALready a String
} else {
Throw 'JSON object should be a HashTable'
Throw 'JSON object should be a HashTable, PSCustomObject or String'
}

# OK, we have a $JSON string now
# OK, we have a Json string now
Write-Verbose "JSON Arguments: $Json"
$ParamSplat.Add('Body', $json)
$ParamSplat.Add('ContentType', 'application/json')
$ParamSplat.Add('Method', 'POST')
$ParamSplat.Method = 'POST'
} else {
# Post a web Form
if ($Form) {
# Output object in JSON notation, if -Verbose is specified
$Json = $Form | ConvertTo-Json -Depth 15
Write-Verbose "Form Arguments: $Json"

$ParamSplat.Add('Method', 'POST')
$ParamSplat.Method = 'POST'
$ParamSplat.Add('Body', $form)
} else {
# Neither Json nor Post, so its a plain request
$ParamSplat.Add('Method', 'GET')
$ParamSplat.Method = 'GET'
}
}

# Override Default Method if passed
if ($Method) {
$ParamSplat.Method = $Method
}

# Write Parameters to Debug channel
Write-Debug "Invoke-RestMethod"
# Write Custom Headers to Debug channel
if ($Headers.Count -gt 0) {
$temp = $Headers | ConvertTo-Json -Compress
Write-Debug " -Headers : $temp"
Write-Debug (" -Headers : {0}" -f ($Headers | ConvertTo-Json -Compress))
}
foreach ($key in $ParamSplat.keys) {
$val = $ParamSplat.Item($key)
Write-Debug " -$key : $val"
Write-Debug (" -{0} : {1}" -f $key, $ParamSplat.Item($key))
}

# Add Custom Headers to the custom Splat
Expand All @@ -113,8 +117,7 @@ Function Invoke-OPNsenseApiRestCommand {
Try {
$result = Invoke-RestMethod @ParamSplat
} Catch {
$ErrorMessage = $_.Exception.Message
Write-Error "An error Occured while contacting the OPNsense server: $ErrorMessage"
Write-Error ("An error Occured while contacting the OPNsense server: {0}" -f $_.Exception.Message)
} Finally {
# Always restore the built-in .NET certificate policy on Windows PS Desktop only
if (-Not $IsPSCoreEdition -And [bool]::Parse($SkipCertificateCheck)) {
Expand Down
16 changes: 9 additions & 7 deletions Private/Invoke-OPNsenseCommand.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ Function Invoke-OPNsenseCommand {

[parameter(Mandatory = $false)][String[]]$Property,

[parameter(Mandatory = $false)][HashTable]$AddProperty
[parameter(Mandatory = $false)][HashTable]$AddProperty,

[parameter(Mandatory = $false)][String]$Method
)

if ($DebugPreference -eq "Inquire") { $DebugPreference = "Continue" }
Expand All @@ -62,17 +64,17 @@ Function Invoke-OPNsenseCommand {
try {
if ($Json) {
$Result = Invoke-OPNsenseApiRestCommand -Uri $Uri -credential $Credentials -Json $Json `
-SkipCertificateCheck:$SkipCertificateCheck -Verbose:$VerbosePreference `
-ErrorAction Stop
-SkipCertificateCheck:$SkipCertificateCheck -Method $Method `
-Verbose:$VerbosePreference -ErrorAction Stop
} else {
if ($Form) {
$Result = Invoke-OPNsenseApiRestCommand -Uri $Uri -credential $Credentials -Form $Form `
-SkipCertificateCheck:$SkipCertificateCheck -Verbose:$VerbosePreference `
-ErrorAction Stop -OutFile $OutFile
-SkipCertificateCheck:$SkipCertificateCheck -OutFile $OutFile -Method $Method `
-Verbose:$VerbosePreference -ErrorAction Stop
} else {
$Result = Invoke-OPNsenseApiRestCommand -Uri $Uri -credential $Credentials `
-SkipCertificateCheck:$SkipCertificateCheck -Verbose:$VerbosePreference `
-ErrorAction Stop
-SkipCertificateCheck:$SkipCertificateCheck -Method $Method `
-Verbose:$VerbosePreference -ErrorAction Stop
}
}
} catch [Microsoft.PowerShell.Commands.WriteErrorException] {
Expand Down
113 changes: 113 additions & 0 deletions Private/Invoke-OPNsenseOpenApiPath.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
<# MIT License
Copyright (c) 2018 fvanroie, NetwiZe.be
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
#>

# Invoke an API call based on the OpenAPI specification file
Function Invoke-OPNsenseOpenApiPath {
# .EXTERNALHELP ../PS_OPNsense.psd1-Help.xml
[CmdletBinding()]
Param(
[parameter(Mandatory = $true, position = 0)]
[ValidateSet("AcmeClient", "ArpScanner", "C-ICAP", "CaptivePortal", "ClamAV", "Collectd", "Cron", "FreeRadius", "FtpProxy", "HAProxy", "HelloWorld",
"IDS", "Iperf", "LLDPd", "MDNSrepeater", "Monit", "Netflow", "NodeExporter", "Nut", "OpenConnect", "Postfix", "Proxy", "ProxySSO", "ProxyUserACl",
"Quagga", "Redis", "Relayd", "Routes", "Rspamd", "ShadowSocks", "Siproxd", "Telegraf", "Tinc", "Tor", "TrafficShaper",
"ZabbixAgent", "ZabbixProxy", "ZeroTier")]
[String]$Module,

[parameter(Mandatory = $true, position = 1)]
[ValidateSet("Get", "Set", "Search", "Toggle", "Add", "Delete",
"Status", "Start", "Restart", "Stop", "Reconfigure", "Test")]
[String]$Action,

[parameter(Mandatory = $true, position = 2)][String]$Object,

[parameter(Mandatory = $false, ParameterSetName = "Json")]
$Body,

# [parameter(Mandatory = $false)][HashTable]$AddProperty,
[parameter(Mandatory = $false)][String]$Uuid,
[parameter(Mandatory = $false)][Boolean]$Enabled
)

# Search the Appropriate API Call for this Action
#$call = Search-OPNsenseOpenApiPath -Module $Module -Action $Action -Object $Object
$call = $OPNsenseOpenApi.$Module.$Action.$Object
if (!$Call) {
Write-Error ("{0} {2} does not implement the {1} action. (#17)" -f $Module, $Action, $Object)
return $null
}

$null, $Module, $Controller, $CmdParams = $Call.Path.Split('/', 4)

# Replace Path parameters with values
foreach ($parameter in $call.parameters) {
if ($parameter.Value.in -eq 'Path') {
$key = '{{{0}}}' -f $parameter.Value.Name
switch ($key) {
'{uuid}' { $value = $uuid }
'{enabled}' { $value = $enabled }
'{disabled}' { $value = -Not $enabled }
default { $value = '' }
}
$CmdParams = $CmdParams.replace($key, $value)
}
}

# Build Parameters Splat
$Splat = @{
'Module' = $Module
'Controller' = $Controller
'Command' = $CmdParams
'Method' = $Call.Method
'Verbose' = $VerbosePreference
'Debug' = $DebugPreference
}
Switch ($Action) {
'get' { $Splat.Add('Property', $Object) }
'search' { $Splat.Add('Property', 'rows') }
default {}
}
if ($Body) {
$Splat.Add('Json', $Body)
}
# Add UUID, except for OPNsense.CaptivePortal.Template already as it already has a UUID
if ($Action -eq 'get' -and $returntype -ne 'OPNsense.CaptivePortal.Template') {
$splat.Add("AddProperty", @{ 'uuid' = $Uuid} )
}

# Run this command thru the Api
$result = Invoke-OPNsenseCommand @Splat

# for OPNsense.CaptivePortal.Template all Templates are returned, select the one with the correct UUID
if ($Action -eq 'get' -and $returntype -eq 'OPNsense.CaptivePortal.Template') {
$result = $result | Where-Object { $_.UUID -eq $Uuid }
}

# Can we cast this into our own object?
if ($returntype) {
Write-Verbose "Converting object to $returntype"
return ConvertTo-OPNsenseObject -TypeName $returntype -InputObject $result
}

# Return PSCustomObject instead
return $result
}
81 changes: 0 additions & 81 deletions Public/Invoke-OPNsenseFunction.ps1

This file was deleted.

0 comments on commit 47900c0

Please sign in to comment.