Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Initialize-PodeOpenApiTable fails to initialize OpenAPI table when DefaultDefinitionTag param is Null #1407

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/Web-AuthBasic.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ Start-PodeServer -Threads 2 {
return @{ Message = 'Invalid details supplied' }
}


# POST request to get current user (since there's no session, authentication will always happen)
Add-PodeRoute -Method Post -Path '/users' -Authentication 'Validate' -ScriptBlock {
Write-PodeJsonResponse -Value @{
Expand Down
93 changes: 93 additions & 0 deletions examples/Web-UsePodeAuth.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<#
.SYNOPSIS
A PowerShell script to set up a Pode server with API key authentication and various route configurations.

.DESCRIPTION
Sets up a Pode server that listens on a specified port, enables request and error logging, and configures API key
authentication. The script uses the `Use-PodeAuth` function to load and apply the authentication defined in
`./auth/SampleAuth.ps1`. The authentication is applied globally to the API routes using `Add-PodeAuthMiddleware`.
The script defines a route to fetch a list of users, which requires authentication using a specified location
for the API key (Header, Query, or Cookie).

.PARAMETER Location
Specifies where the API key is expected. Valid values are 'Header', 'Query', and 'Cookie'. Default is 'Header'.

.EXAMPLE
To run the sample:

```powershell
./Web-UsePodeAuth.ps1
```
Then, make a request to get users with an API key:

```powershell
Invoke-RestMethod -Uri 'http://localhost:8081/api/users' -Method Get -Headers @{ 'X-API-KEY' = 'test-api-key' }
```

.LINK
https://github.com/Badgerati/Pode/blob/develop/examples/Web-UsePodeAuth.ps1

.NOTES
The `Use-PodeAuth` function is used to load the authentication script located at `./auth/SampleAuth.ps1`. The
authentication is then enforced using `Add-PodeAuthMiddleware` to protect the `/api/*` routes.

.NOTES
Author: Pode Team
License: MIT License
#>

param(
[Parameter()]
[ValidateSet('Header', 'Query', 'Cookie')]
[string]
$Location = 'Header'
)

try {
# Determine the script path and Pode module path
$ScriptPath = (Split-Path -Parent -Path $MyInvocation.MyCommand.Path)
$podePath = Split-Path -Parent -Path $ScriptPath

# Import the Pode module from the source path if it exists, otherwise from installed modules
if (Test-Path -Path "$($podePath)/src/Pode.psm1" -PathType Leaf) {
Import-Module "$($podePath)/src/Pode.psm1" -Force -ErrorAction Stop
}
else {
Import-Module -Name 'Pode' -MaximumVersion 2.99 -ErrorAction Stop
}
}
catch { throw }

# or just:
# Import-Module Pode

# create a server, and start listening on port 8081
Start-PodeServer -Threads 2 {

# listen on localhost:8081
Add-PodeEndpoint -Address localhost -Port 8081 -Protocol Http

New-PodeLoggingMethod -File -Name 'requests' | Enable-PodeRequestLogging
New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging

Use-PodeAuth

Add-PodeAuthMiddleware -Name 'globalAuthValidation' -Authentication 'Validate' -Route '/api/*'

# GET request to get list of users (since there's no session, authentication will always happen)
Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock {
Write-PodeJsonResponse -Value @{
Users = @(
@{
Name = 'Deep Thought'
Age = 42
},
@{
Name = 'Leeroy Jenkins'
Age = 1337
}
)
}
}

}
17 changes: 17 additions & 0 deletions examples/auth/SampleAuth.ps1
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# setup bearer auth
New-PodeAuthScheme -ApiKey -Location $Location | Add-PodeAuth -Name 'Validate' -Sessionless -ScriptBlock {
param($key)

# here you'd check a real user storage, this is just for example
if ($key -ieq 'test-api-key') {
return @{
User = @{
ID = 'M0R7Y302'
Name = 'Morty'
Type = 'Human'
}
}
}

return $null
}
14 changes: 11 additions & 3 deletions src/Private/OpenApi.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -1372,17 +1372,25 @@ This is an internal function and may change in future releases of Pode.
function Initialize-PodeOpenApiTable {
param(
[string]
$DefaultDefinitionTag = 'default'
$DefaultDefinitionTag
)
# Check if the provided definition tag is null or empty. If so, set it to 'default'.
if ([string]::IsNullOrEmpty($DefaultDefinitionTag)) {
$DefaultDefinitionTag = 'default'
}

# Initialization of the OpenAPI table with default settings
# Create a hashtable named $OpenAPI to hold various OpenAPI-related configurations and data.
$OpenAPI = @{
# Initialize a stack to manage the Definition Tag selection.
DefinitionTagSelectionStack = [System.Collections.Generic.Stack[System.Object]]::new()
}

# Set the currently selected definition tag
# Set the currently selected definition tag to the provided or default tag.
$OpenAPI['SelectedDefinitionTag'] = $DefaultDefinitionTag

# Initialize the Definitions dictionary with a base OpenAPI object for the selected definition tag
# Initialize the Definitions dictionary with a base OpenAPI object for the selected definition tag.
# The base OpenAPI object is created using the Get-PodeOABaseObject function.
$OpenAPI['Definitions'] = @{ $OpenAPI['SelectedDefinitionTag'] = Get-PodeOABaseObject }

# Return the initialized OpenAPI table
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/_.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ BeforeDiscovery {

# List of directories to exclude
$excludeDirs = @('scripts', 'views', 'static', 'public', 'assets', 'timers', 'modules',
'Authentication', 'certs', 'logs', 'relative', 'routes', 'issues')
'Authentication', 'certs', 'logs', 'relative', 'routes', 'issues','auth')

# Convert exlusion list into single regex pattern for directory matching
$dirSeparator = [IO.Path]::DirectorySeparatorChar
Expand Down
Loading