From 8e6345e4a6eebf8cc45d49f2c4c24bfbe8662611 Mon Sep 17 00:00:00 2001 From: Matthew Kelly Date: Sun, 1 Nov 2020 15:13:18 +0000 Subject: [PATCH 1/4] #618: stop passing WebEvent, as well as Tcp/SmtpEvent --- docs/Hosting/AzureFunctions.md | 6 +- docs/Hosting/IIS.md | 3 +- docs/Hosting/SmtpServer.md | 23 +-- .../Authentication/Inbuilt/UserFile.md | 5 +- .../Authentication/Inbuilt/WindowsAD.md | 5 +- .../Authentication/Methods/Custom.md | 26 ++-- docs/Tutorials/Authentication/Overview.md | 27 +--- docs/Tutorials/Middleware/Overview.md | 12 +- .../Tutorials/Middleware/Types/BodyParsing.md | 4 +- docs/Tutorials/Middleware/Types/CSRF.md | 3 +- docs/Tutorials/Middleware/Types/Sessions.md | 5 +- docs/Tutorials/Misc/UploadFiles.md | 24 ++-- docs/Tutorials/OpenAPI.md | 24 ++-- docs/Tutorials/Routes/Examples/LoginPage.md | 16 +-- docs/Tutorials/Routes/Overview.md | 14 +- .../Routes/Utilities/FunctionsAndModules.md | 6 +- docs/Tutorials/SharedState.md | 23 +-- docs/Tutorials/Views/Pode.md | 4 +- docs/Tutorials/WebSockets.md | 3 +- examples/mail-server.ps1 | 13 +- examples/rest-api.ps1 | 9 +- examples/tcp-server.ps1 | 1 - examples/timers.ps1 | 3 +- examples/web-auth-clientcert.ps1 | 4 +- examples/web-auth-form-ad.ps1 | 8 +- examples/web-auth-form-file.ps1 | 8 +- examples/web-auth-form.ps1 | 8 +- examples/web-csrf.ps1 | 1 - examples/web-gzip-request.ps1 | 3 +- examples/web-pages-https.ps1 | 2 - examples/web-pages-kestrel.ps1 | 9 +- examples/web-pages-using.ps1 | 4 +- examples/web-pages.ps1 | 11 +- examples/web-rest-openapi-shared.ps1 | 9 +- examples/web-rest-openapi-simple.ps1 | 9 +- examples/web-rest-openapi.ps1 | 13 +- examples/web-route-endpoints.ps1 | 3 +- examples/web-route-listen-names.ps1 | 3 +- examples/web-route-protocols.ps1 | 3 +- examples/web-sessions.ps1 | 5 +- src/Misc/default-swagger.html.pode | 1 + src/Private/Authentication.ps1 | 76 +++++----- src/Private/Endware.ps1 | 2 +- src/Private/Logging.ps1 | 6 +- src/Private/Middleware.ps1 | 64 ++++----- src/Private/PodeServer.ps1 | 2 +- src/Private/Serverless.ps1 | 4 +- src/Private/ServiceServer.ps1 | 1 + src/Private/Sessions.ps1 | 28 ++-- src/Private/SmtpServer.ps1 | 4 +- src/Private/TcpServer.ps1 | 2 +- src/Private/Timers.ps1 | 4 +- src/Public/Authentication.ps1 | 11 +- src/Public/Core.ps1 | 2 +- src/Public/Middleware.ps1 | 8 +- src/Public/OpenApi.ps1 | 10 +- src/Public/Routes.ps1 | 14 +- tests/integration/RestApi.Tests.ps1 | 18 +-- tests/integration/Sessions.Tests.ps1 | 7 +- tests/unit/Authentication.Tests.ps1 | 20 +-- tests/unit/Middleware.Tests.ps1 | 135 ++++++++++++------ 61 files changed, 343 insertions(+), 438 deletions(-) diff --git a/docs/Hosting/AzureFunctions.md b/docs/Hosting/AzureFunctions.md index 24d4b5fec..7cc281c4b 100644 --- a/docs/Hosting/AzureFunctions.md +++ b/docs/Hosting/AzureFunctions.md @@ -77,14 +77,12 @@ Start-PodeServer -Request $TriggerMetadata -Type 'AzureFunctions' { # post route to create some data Add-PodeRoute -Method Post -Path $endpoint -ScriptBlock { - param($e) - New-Thing -Name $e.Data['Name'] + New-Thing -Name $WebEvent.Data['Name'] } # put route to update some data Add-PodeRoute -Method Put -Path $endpoint -ScriptBlock { - param($e) - Update-Thing -Name $e.Data['Name'] + Update-Thing -Name $WebEvent.Data['Name'] } } ``` diff --git a/docs/Hosting/IIS.md b/docs/Hosting/IIS.md index 4eea26fba..76b9157c5 100644 --- a/docs/Hosting/IIS.md +++ b/docs/Hosting/IIS.md @@ -105,8 +105,7 @@ Start-PodeServer { Add-PodeAuthIIS -Name 'IISAuth' -Sessionless Add-PodeRoute -Method Get -Path '/test' -Authentication 'IISAuth' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ User = $e.Auth.User } + Write-PodeJsonResponse -Value @{ User = $WebEvent.Auth.User } } } ``` diff --git a/docs/Hosting/SmtpServer.md b/docs/Hosting/SmtpServer.md index 1e453d334..3ad49c5d5 100644 --- a/docs/Hosting/SmtpServer.md +++ b/docs/Hosting/SmtpServer.md @@ -1,6 +1,6 @@ # SMTP Server -Pode has an inbuilt SMTP server which automatically creates a TCP listener on port 25 (unless you specify a different port via the [`Add-PodeEndpoint`](../../Functions/Core/Add-PodeEndpoint) function). +Pode has an inbuilt SMTP server which automatically creates a TCP listener on port 25 (unless you specify a different port via the [`Add-PodeEndpoint`](../../Functions/Core/Add-PodeEndpoint) function). Unlike with web servers that use the Route functions, SMTP servers use the Handler functions, which let you specify logic for handling responses from TCP streams. @@ -8,19 +8,26 @@ To create a Handler for the inbuilt SMTP server you can use the following exampl ```powershell Start-PodeServer { - Add-PodeEndpoint -Address * -Port 25 -Protocol SMTP + Add-PodeEndpoint -Address * -Port 25 -Protocol Smtp Add-PodeHandler -Type Smtp -Name 'Main' -ScriptBlock { - param($email) - - Write-Host $email.From - Write-Host $email.To - Write-Host $email.Data + Write-Host $SmtpEvent.Email.From + Write-Host $SmtpEvent.Email.To + Write-Host $SmtpEvent.Email.Body } } ``` -The SMTP Handler will be passed the current email object, and this will have the following properties: +The SMTP Handler will be passed the a `$SmtpEvent` object, that conatins te Request, Response, and Email: + +| Name | Type | Description | +| ---- | ---- | ----------- | +| Request | object | The raw Request object | +| Response | object | The raw Response object | +| Lockable | hashtable | A synchronized hashtable that can be used with `Lock-PodeObject` | +| Email | hashtable | An object containing data from the email, as seen below | + +The `Email` property contains the following: | Name | Type | Description | | ---- | ---- | ----------- | diff --git a/docs/Tutorials/Authentication/Inbuilt/UserFile.md b/docs/Tutorials/Authentication/Inbuilt/UserFile.md index bf64b3db4..a08d6cd81 100644 --- a/docs/Tutorials/Authentication/Inbuilt/UserFile.md +++ b/docs/Tutorials/Authentication/Inbuilt/UserFile.md @@ -61,7 +61,7 @@ Start-PodeServer { ### User Object -The User object returned, and accessible on Routes, and other functions via the web event's `$e.Auth.User`, will contain the following information: +The User object returned, and accessible on Routes, and other functions via the web event's `$WebEvent.Auth.User`, will contain the following information: | Name | Type | Description | | ---- | ---- | ----------- | @@ -75,8 +75,7 @@ Such as: ```powershell Add-PodeRoute -Method Get -Path '/info' -Authentication 'Login' -ScriptBlock { - param($e) - Write-Host $e.Auth.User.Username + Write-Host $WebEvent.Auth.User.Username } ``` diff --git a/docs/Tutorials/Authentication/Inbuilt/WindowsAD.md b/docs/Tutorials/Authentication/Inbuilt/WindowsAD.md index 2bac38577..52222d16b 100644 --- a/docs/Tutorials/Authentication/Inbuilt/WindowsAD.md +++ b/docs/Tutorials/Authentication/Inbuilt/WindowsAD.md @@ -16,7 +16,7 @@ Start-PodeServer { ### User Object -The User object returned, and accessible on Routes, and other functions via `$e.Auth.User`, will contain the following information: +The User object returned, and accessible on Routes, and other functions via `$WebEvent.Auth.User`, will contain the following information: | Name | Type | Description | | ---- | ---- | ----------- | @@ -34,8 +34,7 @@ Such as: ```powershell Add-PodeRoute -Method Get -Path '/info' -Authentication 'Login' -ScriptBlock { - param($e) - Write-Host $e.Auth.User.Username + Write-Host $WebEvent.Auth.User.Username } ``` diff --git a/docs/Tutorials/Authentication/Methods/Custom.md b/docs/Tutorials/Authentication/Methods/Custom.md index 03399d433..e5a4e6e34 100644 --- a/docs/Tutorials/Authentication/Methods/Custom.md +++ b/docs/Tutorials/Authentication/Methods/Custom.md @@ -14,7 +14,7 @@ The `-ScriptBlock` on [`New-PodeAuthScheme`](../../../../Functions/Authenticatio Start-PodeServer { # define a new custom authentication scheme $custom_scheme = New-PodeAuthScheme -Custom -ScriptBlock { - param($e, $opts) + param($opts) # get client/user/password field names $clientField = (Protect-PodeValue -Value $opts.ClientField -Default 'client') @@ -22,9 +22,9 @@ Start-PodeServer { $passField = (Protect-PodeValue -Value $opts.PasswordField -Default 'password') # get the client/user/password from the request's post data - $client = $e.Data.$clientField - $username = $e.Data.$userField - $password = $e.Data.$passField + $client = $WebEvent.Data.$clientField + $username = $WebEvent.Data.$userField + $password = $WebEvent.Data.$passField # return the data in a array, which will be passed to the validator script return @($client, $username, $password) @@ -67,7 +67,7 @@ For example: Start-PodeServer { # define a new custom authentication scheme $custom_scheme = New-PodeAuthScheme -Custom -ScriptBlock { - param($e, $opts) + param($opts) # get client/user/password field names $clientField = (Protect-PodeValue -Value $opts.ClientField -Default 'client') @@ -75,15 +75,15 @@ Start-PodeServer { $passField = (Protect-PodeValue -Value $opts.PasswordField -Default 'password') # get the client/user/password from the request's post data - $client = $e.Data.$clientField - $username = $e.Data.$userField - $password = $e.Data.$passField + $client = $WebEvent.Data.$clientField + $username = $WebEvent.Data.$userField + $password = $WebEvent.Data.$passField # return the data in a array, which will be passed to the validator script return @($client, $username, $password) } ` -PostValidator { - param($e, $client, $username, $password, $result, $opts) + param($client, $username, $password, $result, $opts) # run any extra post-validation logic @@ -135,7 +135,7 @@ Start-PodeServer { # define a new custom authentication scheme $custom_scheme = New-PodeAuthScheme -Custom -ScriptBlock { - param($e, $opts) + param($opts) # get client/user/pass field names to get from payload $clientField = (Protect-PodeValue -Value $opts.ClientField -Default 'client') @@ -143,9 +143,9 @@ Start-PodeServer { $passField = (Protect-PodeValue -Value $opts.PasswordField -Default 'password') # get the client/user/pass from the post data - $client = $e.Data.$clientField - $username = $e.Data.$userField - $password = $e.Data.$passField + $client = $WebEvent.Data.$clientField + $username = $WebEvent.Data.$userField + $password = $WebEvent.Data.$passField # return the data, to be passed to the validator script return @($client, $username, $password) diff --git a/docs/Tutorials/Authentication/Overview.md b/docs/Tutorials/Authentication/Overview.md index 40b49db80..616ed5f19 100644 --- a/docs/Tutorials/Authentication/Overview.md +++ b/docs/Tutorials/Authentication/Overview.md @@ -30,7 +30,7 @@ Where as the following example defines a Custom scheme that retrieves the user's ```powershell Start-PodeServer { $custom_type = New-PodeAuthScheme -Custom -ScriptBlock { - param($e, $opts) + param($opts) # get client/user/pass field names to get from payload $clientField = (Protect-PodeValue -Value $opts.ClientField -Default 'client') @@ -38,9 +38,9 @@ Start-PodeServer { $passField = (Protect-PodeValue -Value $opts.PasswordField -Default 'password') # get the client/user/pass from the post data - $client = $e.Data.$clientField - $username = $e.Data.$userField - $password = $e.Data.$passField + $client = $WebEvent.Data.$clientField + $username = $WebEvent.Data.$userField + $password = $WebEvent.Data.$passField # return the data as an array, to be passed to the validator script return @($client, $username, $password) @@ -133,21 +133,6 @@ WWW-Authenticate: Basic realm="Enter creds to access site" !!! note If no Realm was set then it would just look as follows: `WWW-Authenticate: Basic` -#### WebEvent - -By default the web event for the current request is not supplied to the validator's ScriptBlock. If you ever need the web event though, such as for accessing other request details like a client certificate, then you can supply the `-PassEvent` switch on [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth). With this, Pode will supply the current web event as the first parameter: - -```powershell -Start-PodeServer { - New-PodeAuthScheme -Basic | Add-PodeAuth -Name 'Login' -Sessionless -PassEvent -ScriptBlock { - param($e, $username, $pass) - # logic to check user - # logic to check client cert (found at: $e.Request.ClientCertificate) - return @{ 'user' = $user } - } -} -``` - ### Routes/Middleware To use an authentication on a specific route, you can use the `-Authentication` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function; this takes the Name supplied to the `-Name` parameter on [`Add-PodeAuth`](../../../Functions/Authentication/Add-PodeAuth). This will set the authentication up to run before other route middleware. @@ -192,10 +177,8 @@ The following example get the user's name from the `Auth` object: ```powershell Add-PodeRoute -Method Get -Path '/' -Authentication 'Login' -Login -ScriptBlock { - param($e) - Write-PodeViewResponse -Path 'index' -Data @{ - 'Username' = $e.Auth.User.Name + 'Username' = $WebEvent.Auth.User.Name } } ``` diff --git a/docs/Tutorials/Middleware/Overview.md b/docs/Tutorials/Middleware/Overview.md index 59f160c22..2834c0b14 100644 --- a/docs/Tutorials/Middleware/Overview.md +++ b/docs/Tutorials/Middleware/Overview.md @@ -19,11 +19,8 @@ The following example is middleware that observes the user agent of the request. ```powershell Start-PodeServer { Add-PodeMiddleware -Name 'BlockPowershell' -ScriptBlock { - # event which contains the Request/Response, and other keys - param($event) - # if the user agent is powershell, deny access - if ($event.Request.UserAgent -ilike '*powershell*') { + if ($WebEvent.Request.UserAgent -ilike '*powershell*') { # forbidden Set-PodeResponseStatus -Code 403 @@ -32,7 +29,7 @@ Start-PodeServer { } # create a new key on the event for the next middleware/route - $event.Agent = $event.Request.UserAgent + $WebEvent.Agent = $WebEvent.Request.UserAgent # continue processing other middleware return $true @@ -63,11 +60,8 @@ The following example defines a `scriptblock` to reject calls that come from a s Start-PodeServer { # custom middleware to reject access to a specific IP address $reject_ip = { - # same event object as supplied to global middleware/routes - param($event) - # forbid access to the stated IP address - if ($event.Request.RemoteEndPoint.Address.IPAddressToString -ieq '10.10.1.8') { + if ($WebEvent.Request.RemoteEndPoint.Address.IPAddressToString -ieq '10.10.1.8') { Set-PodeResponseStatus -Code 403 return $false } diff --git a/docs/Tutorials/Middleware/Types/BodyParsing.md b/docs/Tutorials/Middleware/Types/BodyParsing.md index f39da3bb1..318b47218 100644 --- a/docs/Tutorials/Middleware/Types/BodyParsing.md +++ b/docs/Tutorials/Middleware/Types/BodyParsing.md @@ -29,10 +29,8 @@ This can then be accessed the normal way within a Route from the `.Data` object ```powershell Add-PodeRoute -Method Post -Path '/' -ScriptBlock { - param($e) - # if using the above parser, .Data here will just be a plain string - Write-PodeTextResponse -Value $e.Data + Write-PodeTextResponse -Value $WebEvent.Data } ``` diff --git a/docs/Tutorials/Middleware/Types/CSRF.md b/docs/Tutorials/Middleware/Types/CSRF.md index e99fec634..e3322a06b 100644 --- a/docs/Tutorials/Middleware/Types/CSRF.md +++ b/docs/Tutorials/Middleware/Types/CSRF.md @@ -88,8 +88,7 @@ Start-PodeServer { # POST route for form which will require the csrf token from above Add-PodeRoute -Method Post -Path '/token' -ScriptBlock { - param($e) - Add-PodeFlashMessage -Name 'message' -Message $e.Data['message'] + Add-PodeFlashMessage -Name 'message' -Message $WebEvent.Data['message'] Move-PodeResponseUrl -Url '/' } } diff --git a/docs/Tutorials/Middleware/Types/Sessions.md b/docs/Tutorials/Middleware/Types/Sessions.md index f016412e0..c0cc4036b 100644 --- a/docs/Tutorials/Middleware/Types/Sessions.md +++ b/docs/Tutorials/Middleware/Types/Sessions.md @@ -97,9 +97,8 @@ Start-PodeServer { Enable-PodeSessionMiddleware -Secret 'schwifty' -Duration 120 Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($s) - $s.Session.Data.Views++ - Write-PodeJsonResponse -Value @{ 'Views' = $s.Session.Data.Views } + $WebEvent.Session.Data.Views++ + Write-PodeJsonResponse -Value @{ 'Views' = $WebEvent.Session.Data.Views } } } ``` diff --git a/docs/Tutorials/Misc/UploadFiles.md b/docs/Tutorials/Misc/UploadFiles.md index de6287eb0..b00763d7b 100644 --- a/docs/Tutorials/Misc/UploadFiles.md +++ b/docs/Tutorials/Misc/UploadFiles.md @@ -1,6 +1,6 @@ # Uploading Files -Pode's inbuilt middleware supports parsing a request's body/payload and query string, and this also extends to uploading files via a `
`. Like how POST data can be accessed in a Route via the passed [web event](../../WebEvent) as `$e.Data[]`, uploaded files can be accessed via `$e.Files[]`. +Pode's inbuilt middleware supports parsing a request's body/payload and query string, and this also extends to uploading files via a ``. Like how POST data can be accessed in a Route via the passed [web event](../../WebEvent) as `$WebEvent.Data[]`, uploaded files can be accessed via `$WebEvent.Files[]`. !!! important In order for uploaded files to work, your `` must contain `enctype="multipart/form-data"` @@ -42,14 +42,14 @@ The inputs will be POSTed to the server, and accessible via the [web event](../. For the `.Data`: ```powershell -$e.Data['username'] # the username entered -$e.Data['password'] # the password entered -$e.Data['avatar'] # the name of the file (assume image.png) +$WebEvent.Data['username'] # the username entered +$WebEvent.Data['password'] # the password entered +$WebEvent.Data['avatar'] # the name of the file (assume image.png) ``` For the `.Files`: ```powershell -$e.Files['image.png'] # the bytes of the uploaded file +$WebEvent.Files['image.png'] # the bytes of the uploaded file ``` ## Script @@ -72,13 +72,11 @@ Start-PodeServer { # POST request to save the avatar and create user Add-PodeRoute -Method Post -Path '/signup' -ScriptBlock { - param($e) - # do some logic here to create user - New-User -Username $e.Data['username'] -Password $e.Data['password'] + New-User -Username $WebEvent.Data['username'] -Password $WebEvent.Data['password'] - # upload the avatar - this will retrieve the filename from $e.Data, - # and the bytes from $e.Files, saving to the server's root path + # upload the avatar - this will retrieve the filename from $WebEvent.Data, + # and the bytes from $WebEvent.Files, saving to the server's root path Save-PodeRequestFile -Key 'avatar' } @@ -91,14 +89,12 @@ If you need to save the uploaded file elsewhere, then you can retrieve the raw b ```powershell Add-PodeRoute -Method Post -Path '/upload' -ScriptBlock { - param($e) - # using .Data will get you the file's name - $filename = $e.Data['avatar'] + $filename = $WebEvent.Data['avatar'] # with the filename, you can get the file's bytes from .File # as well as the Bytes, you can also get the ContentType - $bytes = $e.Files[$filename].Bytes + $bytes = $WebEvent.Files[$filename].Bytes # with the bytes, you can upload the file where ever you want } diff --git a/docs/Tutorials/OpenAPI.md b/docs/Tutorials/OpenAPI.md index 9650e9957..c70444ff3 100644 --- a/docs/Tutorials/OpenAPI.md +++ b/docs/Tutorials/OpenAPI.md @@ -41,8 +41,7 @@ For example: ```powershell Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) - if ($e.Query.openapi -eq 1) { + if ($WebEvent.Query.openapi -eq 1) { Get-PodeOpenApiDefinition | Write-PodeJsonResponse } } @@ -85,10 +84,9 @@ Whereas the following is a more complex definition, which also defines the respo ```powershell Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) Write-PodeJsonResponse -Value @{ Name = 'Rick' - UserId = $e.Parameters['userId'] + UserId = $WebEvent.Parameters['userId'] } } -PassThru | Add-PodeOAResponse -StatusCode 200 -Description 'A user object' -ContentSchemas @{ @@ -127,10 +125,9 @@ For example, to create some integer `userId` parameter that is supplied in the p ```powershell Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) Write-PodeJsonResponse -Value @{ Name = 'Rick' - UserId = $e.Parameters['userId'] + UserId = $WebEvent.Parameters['userId'] } } -PassThru | Set-PodeOARequest -Parameters @( @@ -142,10 +139,9 @@ Whereas you could use the next example to define 2 query parameters, both string ```powershell Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { - param($e) Write-PodeJsonResponse -Value @{ Name = 'Rick' - UserId = $e.Query['name'] + UserId = $WebEvent.Query['name'] } } -PassThru | Set-PodeOARequest -Parameters @( @@ -162,10 +158,9 @@ For example, to define a request JSON payload of some `userId` and `name` you co ```powershell Add-PodeRoute -Method Patch -Path '/api/users' -ScriptBlock { - param($e) Write-PodeJsonResponse -Value @{ - Name = $e.Data.name - UserId = $e.Data.userId + Name = $WebEvent.Data.name + UserId = $WebEvent.Data.userId } } -PassThru | Set-PodeOARequest -RequestBody ( @@ -209,10 +204,9 @@ Add-PodeOAComponentSchema -Name 'UserSchema' -Schema ( # reuse the above schema in a response Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) Write-PodeJsonResponse -Value @{ Name = 'Rick' - UserId = $e.Parameters['userId'] + UserId = $WebEvent.Parameters['userId'] Age = 42 } } -PassThru | @@ -239,7 +233,6 @@ Add-PodeOAComponentRequestBody -Name 'UserBody' -Required -ContentSchemas @{ # use the request body in a route Add-PodeRoute -Method Patch -Path '/api/users' -ScriptBlock { - param($e) Set-PodeResponseStatus -StatusCode 200 } -PassThru | Set-PodeOARequest -RequestBody (New-PodeOARequestBody -Reference 'UserBody') @@ -267,10 +260,9 @@ New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In P # use this parameter in a route Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) Write-PodeJsonResponse -Value @{ Name = 'Rick' - UserId = $e.Parameters['userId'] + UserId = $WebEvent.Parameters['userId'] } } -PassThru | Set-PodeOARequest -Parameters @(ConvertTo-PodeOAParameter -Reference 'UserId') diff --git a/docs/Tutorials/Routes/Examples/LoginPage.md b/docs/Tutorials/Routes/Examples/LoginPage.md index 3fa449e3b..a1bf6138b 100644 --- a/docs/Tutorials/Routes/Examples/LoginPage.md +++ b/docs/Tutorials/Routes/Examples/LoginPage.md @@ -67,13 +67,11 @@ Below is the Route for the root (`/`) endpoint. This will check the cookies in t ```powershell Add-PodeRoute -Method Get -Path '/' -Authentication 'Login' -ScriptBlock { - param($e) - - $e.Session.Data.Views++ + $WebEvent.Session.Data.Views++ Write-PodeViewResponse -Path 'auth-home' -Data @{ - Username = $e.Auth.User.Name; - Views = $e.Session.Data.Views; + Username = $WebEvent.Auth.User.Name; + Views = $WebEvent.Session.Data.Views; } } ``` @@ -135,13 +133,11 @@ Start-PodeServer -Thread 2 { # the "GET /" endpoint for the homepage Add-PodeRoute -Method Get -Path '/' -Authentication 'Login' -ScriptBlock { - param($e) - - $e.Session.Data.Views++ + $WebEvent.Session.Data.Views++ Write-PodeViewResponse -Path 'auth-home' -Data @{ - Username = $e.Auth.User.Name; - Views = $e.Session.Data.Views; + Username = $WebEvent.Auth.User.Name; + Views = $WebEvent.Session.Data.Views; } } diff --git a/docs/Tutorials/Routes/Overview.md b/docs/Tutorials/Routes/Overview.md index c258cf1b6..c74e0cb7e 100644 --- a/docs/Tutorials/Routes/Overview.md +++ b/docs/Tutorials/Routes/Overview.md @@ -43,10 +43,8 @@ Start-PodeServer { Add-PodeEndpoint -Address * -Port 8080 -Protocol Http Add-PodeRoute -Method Post -Path '/users' -ScriptBlock { - param($s) - # get the user - $user = Get-DummyUser -UserId $s.Data.userId + $user = Get-DummyUser -UserId $WebEvent.Data.userId # return the user Write-PodeJsonResponse -Value @{ @@ -67,7 +65,7 @@ Invoke-WebRequest -Uri 'http://localhost:8080/users' -Method Post -Body '{ "user The `ContentType` is required as it informs Pode on how to parse the requests payload. For example, if the content type were `application/json`, then Pode will attempt to parse the body of the request as JSON - converting it to a hashtable. !!! important - On PowerShell 4 and 5, referencing JSON data on `$s.Data` must be done as `$s.Data.userId`. This also works in PowerShell 6+, but you can also use `$s.Data['userId']` on PowerShell 6+. + On PowerShell 4 and 5, referencing JSON data on `$WebEvent.Data` must be done as `$WebEvent.Data.userId`. This also works in PowerShell 6+, but you can also use `$WebEvent.Data['userId']` on PowerShell 6+. ## Query Strings @@ -78,10 +76,8 @@ Start-PodeServer { Add-PodeEndpoint -Address * -Port 8080 -Protocol Http Add-PodeRoute -Method Get -Path '/users' -ScriptBlock { - param($s) - # get the user - $user = Get-DummyUser -UserId $s.Query['userId'] + $user = Get-DummyUser -UserId $WebEvent.Query['userId'] # return the user Write-PodeJsonResponse -Value @{ @@ -107,10 +103,8 @@ Start-PodeServer { Add-PodeEndpoint -Address * -Port 8080 -Protocol Http Add-PodeRoute -Method Get -Path '/users/:userId' -ScriptBlock { - param($s) - # get the user - $user = Get-DummyUser -UserId $s.Parameters['userId'] + $user = Get-DummyUser -UserId $WebEvent.Parameters['userId'] # return the user Write-PodeJsonResponse -Value @{ diff --git a/docs/Tutorials/Routes/Utilities/FunctionsAndModules.md b/docs/Tutorials/Routes/Utilities/FunctionsAndModules.md index df49d5396..a86142aff 100644 --- a/docs/Tutorials/Routes/Utilities/FunctionsAndModules.md +++ b/docs/Tutorials/Routes/Utilities/FunctionsAndModules.md @@ -16,15 +16,13 @@ This will generate two Routes, similar to as if you did the below: ```powershell Add-PodeRoute -Method Get -Path '/Get-ChildItem' -ScriptBlock { - param($e) - $parameters = $e.Data + $parameters = $WebEvent.Data $result = (Get-ChildItem @parameters) Write-PodeJsonResponse -Value $result -Depth 1 } Add-PodeRoute -Method Post -Path '/Invoke-Expression' -ScriptBlock { - param($e) - $parameters = $e.Data + $parameters = $WebEvent.Data $result = (Invoke-Expression @parameters) Write-PodeJsonResponse -Value $result -Depth 1 } diff --git a/docs/Tutorials/SharedState.md b/docs/Tutorials/SharedState.md index 295b8e8ed..f119b7a18 100644 --- a/docs/Tutorials/SharedState.md +++ b/docs/Tutorials/SharedState.md @@ -23,9 +23,7 @@ An example of setting a hashtable variable in the state is as follows: ```powershell Start-PodeServer { Add-PodeTimer -Name 'do-something' -Interval 5 -ScriptBlock { - param($e) - - Lock-PodeObject -Object $e.Lockable { + Lock-PodeObject -Object $TimerEvent.Lockable { Set-PodeState -Name 'data' -Value @{ 'Name' = 'Rick Sanchez' } | Out-Null } } @@ -41,10 +39,9 @@ An example of retrieving a value from the state is as follows: ```powershell Start-PodeServer { Add-PodeTimer -Name 'do-something' -Interval 5 -ScriptBlock { - param($e) $value = $null - Lock-PodeObject -Object $e.Lockable { + Lock-PodeObject -Object $TimerEvent.Lockable { $value = (Get-PodeState -Name 'data') } @@ -62,9 +59,7 @@ An example of removing a variable from the state is as follows: ```powershell Start-PodeServer { Add-PodeTimer -Name 'do-something' -Interval 5 -ScriptBlock { - param($e) - - Lock-PodeObject -Object $e.Lockable { + Lock-PodeObject -Object $TimerEvent.Lockable { Remove-PodeState -Name 'data' | Out-Null } } @@ -119,10 +114,8 @@ Start-PodeServer { # timer to add a random number to the shared state Add-PodeTimer -Name 'forever' -Interval 2 -ScriptBlock { - param($e) - # ensure we're thread safe - Lock-PodeObject -Object $e.Lockable { + Lock-PodeObject -Object $TimerEvent.Lockable { # attempt to get the hashtable from the state $hash = (Get-PodeState -Name 'hash') @@ -137,10 +130,8 @@ Start-PodeServer { # route to return the value of the hashtable from shared state Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) - # again, ensure we're thread safe - Lock-PodeObject -Object $e.Lockable { + Lock-PodeObject -Object $WebEvent.Lockable { # get the hashtable from the state and return it $hash = (Get-PodeState -Name 'hash') @@ -150,10 +141,8 @@ Start-PodeServer { # route to remove the hashtable from shared state Add-PodeRoute -Method Delete -Path '/' -ScriptBlock { - param($e) - # ensure we're thread safe - Lock-PodeObject -Object $e.Lockable { + Lock-PodeObject -Object $WebEvent.Lockable { # remove the hashtable from the state Remove-PodeState -Name 'hash' | Out-Null diff --git a/docs/Tutorials/Views/Pode.md b/docs/Tutorials/Views/Pode.md index 4aa8f66af..a428cbd68 100644 --- a/docs/Tutorials/Views/Pode.md +++ b/docs/Tutorials/Views/Pode.md @@ -54,10 +54,8 @@ Start-PodeServer { # render the search.pode view Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($event) - # some logic to get accounts - $query = $event.Query['query'] + $query = $WebEvent.Query['query'] $accounts = Find-Account -Query $query # render the file diff --git a/docs/Tutorials/WebSockets.md b/docs/Tutorials/WebSockets.md index 72a963b5a..a28de5962 100644 --- a/docs/Tutorials/WebSockets.md +++ b/docs/Tutorials/WebSockets.md @@ -25,8 +25,7 @@ To broadcast some data to all clients from a POST route, you could use the follo ```powershell Add-PodeRoute -Method Post -Path '/broadcast' -ScriptBlock { - param($e) - Send-PodeSignal -Value @{ Message = $e.Data['message'] } + Send-PodeSignal -Value @{ Message = $WebEvent.Data['message'] } } ``` diff --git a/examples/mail-server.ps1 b/examples/mail-server.ps1 index 11edddee0..c160aced6 100644 --- a/examples/mail-server.ps1 +++ b/examples/mail-server.ps1 @@ -12,7 +12,7 @@ Send-MailMessage -SmtpServer localhost -To 'to@pode.com' -From 'from@pode.com' - # create a server, and start listening on port 25 Start-PodeServer -Threads 2 { - Add-PodeEndpoint -Address localhost -Protocol SMTP + Add-PodeEndpoint -Address localhost -Protocol Smtp # enable logging New-PodeLoggingMethod -Terminal | Enable-PodeErrorLogging @@ -22,16 +22,15 @@ Start-PodeServer -Threads 2 { # setup an smtp handler Add-PodeHandler -Type Smtp -Name 'Main' -ScriptBlock { - param($e) Write-Host '- - - - - - - - - - - - - - - - - -' - Write-Host $e.Email.From - Write-Host $e.Email.To + Write-Host $SmtpEvent.Email.From + Write-Host $SmtpEvent.Email.To Write-Host '|' - Write-Host $e.Email.Body + Write-Host $SmtpEvent.Email.Body Write-Host '|' - Write-Host $e.Email.Data + Write-Host $SmtpEvent.Email.Data Write-Host '|' - $e.Email | Out-Default + $SmtpEvent.Email | Out-Default Write-Host '- - - - - - - - - - - - - - - - - -' } diff --git a/examples/rest-api.ps1 b/examples/rest-api.ps1 index cfc99ccb1..9599c37bc 100644 --- a/examples/rest-api.ps1 +++ b/examples/rest-api.ps1 @@ -16,20 +16,17 @@ Start-PodeServer { # can be hit by sending a POST request to "localhost:8086/api/test" Add-PodeRoute -Method Post -Path '/api/test' -ContentType 'application/json' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ 'hello' = 'world'; 'name' = $e.Data['name']; } + Write-PodeJsonResponse -Value @{ 'hello' = 'world'; 'name' = $WebEvent.Data['name']; } } # returns details for an example user Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ 'user' = $e.Parameters['userId']; } + Write-PodeJsonResponse -Value @{ 'user' = $WebEvent.Parameters['userId']; } } # returns details for an example user Add-PodeRoute -Method Get -Path '/api/users/:userId/messages' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ 'user' = $e.Parameters['userId']; } + Write-PodeJsonResponse -Value @{ 'user' = $WebEvent.Parameters['userId']; } } } \ No newline at end of file diff --git a/examples/tcp-server.ps1 b/examples/tcp-server.ps1 index 5eff5a223..0b6153996 100644 --- a/examples/tcp-server.ps1 +++ b/examples/tcp-server.ps1 @@ -14,7 +14,6 @@ Start-PodeServer -Threads 2 { # setup a tcp handler Add-PodeHandler -Type Tcp -Name 'Main' -ScriptBlock { - param($e) Write-PodeTcpClient -Message 'gief data' $msg = (Read-PodeTcpClient) Write-Host $msg diff --git a/examples/timers.ps1 b/examples/timers.ps1 index c9005d6d0..8316ef8ad 100644 --- a/examples/timers.ps1 +++ b/examples/timers.ps1 @@ -42,8 +42,7 @@ Start-PodeServer { # create a new timer via a route Add-PodeRoute -Method Get -Path '/api/timer' -ScriptBlock { - param($event) - $query = $event.Query + $query = $WebEvent.Query Add-PodeTimer -Name $query['Name'] -Interval $query['Seconds'] -ScriptBlock { # logic diff --git a/examples/web-auth-clientcert.ps1 b/examples/web-auth-clientcert.ps1 index c8eaebff8..3b76551a7 100644 --- a/examples/web-auth-clientcert.ps1 +++ b/examples/web-auth-clientcert.ps1 @@ -34,14 +34,12 @@ Start-PodeServer { # GET request for web page at "/" Add-PodeRoute -Method Get -Path '/' -Authentication 'Validate' -ScriptBlock { - param($e) - #$e.Request.ClientCertificate | out-default + #$WebEvent.Request.ClientCertificate | out-default Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @(1, 2, 3); } } # GET request throws fake "500" server error status code Add-PodeRoute -Method Get -Path '/error' -Authentication 'Validate' -ScriptBlock { - param($e) Set-PodeResponseStatus -Code 500 } diff --git a/examples/web-auth-form-ad.ps1 b/examples/web-auth-form-ad.ps1 index 0464dafde..8cf3d648b 100644 --- a/examples/web-auth-form-ad.ps1 +++ b/examples/web-auth-form-ad.ps1 @@ -34,13 +34,11 @@ Start-PodeServer -Threads 2 { # home page: # redirects to login page if not authenticated Add-PodeRoute -Method Get -Path '/' -Authentication Login -ScriptBlock { - param($e) - - $e.Session.Data.Views++ + $WebEvent.Session.Data.Views++ Write-PodeViewResponse -Path 'auth-home' -Data @{ - 'Username' = $e.Auth.User.Name; - 'Views' = $e.Session.Data.Views; + Username = $WebEvent.Auth.User.Name + Views = $WebEvent.Session.Data.Views } } diff --git a/examples/web-auth-form-file.ps1 b/examples/web-auth-form-file.ps1 index 3b91f77ff..7b7773d80 100644 --- a/examples/web-auth-form-file.ps1 +++ b/examples/web-auth-form-file.ps1 @@ -37,13 +37,11 @@ Start-PodeServer -Threads 2 { # home page: # redirects to login page if not authenticated Add-PodeRoute -Method Get -Path '/' -Authentication Login -ScriptBlock { - param($e) - - $e.Session.Data.Views++ + $WebEvent.Session.Data.Views++ Write-PodeViewResponse -Path 'auth-home' -Data @{ - 'Username' = $e.Auth.User.Name; - 'Views' = $e.Session.Data.Views; + Username = $WebEvent.Auth.User.Name + Views = $WebEvent.Session.Data.Views } } diff --git a/examples/web-auth-form.ps1 b/examples/web-auth-form.ps1 index c01b15e49..2aa9aba53 100644 --- a/examples/web-auth-form.ps1 +++ b/examples/web-auth-form.ps1 @@ -51,13 +51,11 @@ Start-PodeServer -Threads 2 { # home page: # redirects to login page if not authenticated Add-PodeRoute -Method Get -Path '/' -Authentication Login -ScriptBlock { - param($e) - - $e.Session.Data.Views++ + $WebEvent.Session.Data.Views++ Write-PodeViewResponse -Path 'auth-home' -Data @{ - Username = $e.Auth.User.Name; - Views = $e.Session.Data.Views; + Username = $WebEvent.Auth.User.Name + Views = $WebEvent.Session.Data.Views } } diff --git a/examples/web-csrf.ps1 b/examples/web-csrf.ps1 index 65d8727d3..465483d17 100644 --- a/examples/web-csrf.ps1 +++ b/examples/web-csrf.ps1 @@ -42,7 +42,6 @@ Start-PodeServer -Threads 2 { # POST route for form with and without csrf token Add-PodeRoute -Method Post -Path '/token' -ScriptBlock { - param($e) Move-PodeResponseUrl -Url '/' } diff --git a/examples/web-gzip-request.ps1 b/examples/web-gzip-request.ps1 index 129d2c03b..9df34e0fa 100644 --- a/examples/web-gzip-request.ps1 +++ b/examples/web-gzip-request.ps1 @@ -14,8 +14,7 @@ Start-PodeServer -Threads 2 { # GET request that recieves gzip'd json Add-PodeRoute -Method Post -Path '/users' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value $e.Data + Write-PodeJsonResponse -Value $WebEvent.Data } } \ No newline at end of file diff --git a/examples/web-pages-https.ps1 b/examples/web-pages-https.ps1 index 6221dc75a..5f9ba9e09 100644 --- a/examples/web-pages-https.ps1 +++ b/examples/web-pages-https.ps1 @@ -21,13 +21,11 @@ Start-PodeServer { # GET request for web page at "/" Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @(1, 2, 3); } } # GET request throws fake "500" server error status code Add-PodeRoute -Method Get -Path '/error' -ScriptBlock { - param($e) Set-PodeResponseStatus -Code 500 } diff --git a/examples/web-pages-kestrel.ps1 b/examples/web-pages-kestrel.ps1 index 79e5372c8..632f1e5c1 100644 --- a/examples/web-pages-kestrel.ps1 +++ b/examples/web-pages-kestrel.ps1 @@ -49,8 +49,7 @@ Start-PodeServer -Threads 2 -ListenerType Kestrel { # GET request for web page on "localhost:8085/" Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) - # $e.Request | Write-PodeLog -Name 'custom' + # $WebEvent.Request | Write-PodeLog -Name 'custom' Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @(1, 2, 3); } } @@ -66,8 +65,7 @@ Start-PodeServer -Threads 2 -ListenerType Kestrel { # GET request that redirects to same host, just different port Add-PodeRoute -Method Get -Path '/redirect-port' -ScriptBlock { - param($event) - if ($event.Request.Url.Port -ne 8086) { + if ($WebEvent.Request.Url.Port -ne 8086) { Move-PodeResponseUrl -Port 8086 } else { @@ -82,8 +80,7 @@ Start-PodeServer -Threads 2 -ListenerType Kestrel { # GET request with parameters Add-PodeRoute -Method Get -Path '/:userId/details' -ScriptBlock { - param($event) - Write-PodeJsonResponse -Value @{ 'userId' = $event.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ 'userId' = $WebEvent.Parameters['userId'] } } # ALL request, that supports every method and it a default drop route diff --git a/examples/web-pages-using.ps1 b/examples/web-pages-using.ps1 index 5cd562738..df5babb99 100644 --- a/examples/web-pages-using.ps1 +++ b/examples/web-pages-using.ps1 @@ -49,13 +49,11 @@ Start-PodeServer -Threads 2 { # GET request for web page on "localhost:8090/" Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) - $using:innerfoo | Out-Default $using:outerfoo | Out-Default $using:innerfoo | Out-Default - $e.Method | Out-Default + $WebEvent.Method | Out-Default Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @(1, 2, 3); } } diff --git a/examples/web-pages.ps1 b/examples/web-pages.ps1 index fe090593f..b17e96e85 100644 --- a/examples/web-pages.ps1 +++ b/examples/web-pages.ps1 @@ -32,11 +32,13 @@ Start-PodeServer -Threads 2 { Set-PodeViewEngine -Type Pode # wire up a custom logger + #TODO: can we remove this param, for a "$LogItem"? $logType = New-PodeLoggingMethod -Custom -ScriptBlock { param($item) $item.HttpMethod | Out-Default } + #TODO: can we remove this param, for a "$LogItem"? $logType | Add-PodeLogger -Name 'custom' -ScriptBlock { param($item) return @{ @@ -46,8 +48,7 @@ Start-PodeServer -Threads 2 { # GET request for web page on "localhost:8085/" Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) - # $e.Request | Write-PodeLog -Name 'custom' + # $WebEvent.Request | Write-PodeLog -Name 'custom' Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @(1, 2, 3); } } @@ -63,8 +64,7 @@ Start-PodeServer -Threads 2 { # GET request that redirects to same host, just different port Add-PodeRoute -Method Get -Path '/redirect-port' -ScriptBlock { - param($event) - if ($event.Request.Url.Port -ne 8086) { + if ($WebEvent.Request.Url.Port -ne 8086) { Move-PodeResponseUrl -Port 8086 } else { @@ -79,8 +79,7 @@ Start-PodeServer -Threads 2 { # GET request with parameters Add-PodeRoute -Method Get -Path '/:userId/details' -ScriptBlock { - param($event) - Write-PodeJsonResponse -Value @{ 'userId' = $event.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ 'userId' = $WebEvent.Parameters['userId'] } } # ALL request, that supports every method and it a default drop route diff --git a/examples/web-rest-openapi-shared.ps1 b/examples/web-rest-openapi-shared.ps1 index e707d0359..c793cde1d 100644 --- a/examples/web-rest-openapi-shared.ps1 +++ b/examples/web-rest-openapi-shared.ps1 @@ -53,8 +53,7 @@ Start-PodeServer { Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Parameters['userId'] } } -PassThru | Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | Set-PodeOARequest -Parameters @( @@ -64,8 +63,7 @@ Start-PodeServer { Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Query['userId'] } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Query['userId'] } } -PassThru | Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | Set-PodeOARequest -Parameters @( @@ -75,8 +73,7 @@ Start-PodeServer { Add-PodeRoute -Method Post -Path '/api/users' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Data.userId } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Data.userId } } -PassThru | Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | Set-PodeOARequest -RequestBody ( diff --git a/examples/web-rest-openapi-simple.ps1 b/examples/web-rest-openapi-simple.ps1 index f6a340519..0af964215 100644 --- a/examples/web-rest-openapi-simple.ps1 +++ b/examples/web-rest-openapi-simple.ps1 @@ -21,8 +21,7 @@ Start-PodeServer { Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Parameters['userId'] } } -PassThru | Set-PodeOARequest -Parameters @( (New-PodeOAIntProperty -Name 'userId' -Enum @(100,300,999) -Required | ConvertTo-PodeOAParameter -In Path) @@ -30,8 +29,7 @@ Start-PodeServer { Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Query['userId'] } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Query['userId'] } } -PassThru | Set-PodeOARequest -Parameters @( (New-PodeOAIntProperty -Name 'userId' -Required | ConvertTo-PodeOAParameter -In Query) @@ -39,8 +37,7 @@ Start-PodeServer { Add-PodeRoute -Method Post -Path '/api/users' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = $e.Data.Name; UserId = $e.Data.UserId } + Write-PodeJsonResponse -Value @{ Name = $WebEvent.Data.Name; UserId = $WebEvent.Data.UserId } } -PassThru | Set-PodeOARequest -RequestBody ( New-PodeOARequestBody -Required -ContentSchemas @{ diff --git a/examples/web-rest-openapi.ps1 b/examples/web-rest-openapi.ps1 index 8ff27692f..1e51408d8 100644 --- a/examples/web-rest-openapi.ps1 +++ b/examples/web-rest-openapi.ps1 @@ -39,8 +39,7 @@ Start-PodeServer { Add-PodeRoute -Method Get -Path '/api/users/:userId' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Parameters['userId'] } } -PassThru | Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | Set-PodeOARequest -Parameters @( @@ -55,8 +54,7 @@ Start-PodeServer { Add-PodeRoute -Method Get -Path '/api/users' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Query['userId'] } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Query['userId'] } } -PassThru | Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | Set-PodeOARequest -Parameters @( @@ -66,8 +64,7 @@ Start-PodeServer { Add-PodeRoute -Method Post -Path '/api/users' -Authentication Validate -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $e.Data.userId } + Write-PodeJsonResponse -Value @{ Name = 'Rick'; UserId = $WebEvent.Data.userId } } -PassThru | Set-PodeOARouteInfo -Summary 'A cool summary' -Tags 'Users' -PassThru | Set-PodeOARequest -RequestBody ( @@ -78,10 +75,8 @@ Start-PodeServer { Add-PodeOAResponse -StatusCode 200 -Description 'A user object' Add-PodeRoute -Method Put -Path '/api/users' -ScriptBlock { - param($e) - $users = @() - foreach ($id in $e.Data) { + foreach ($id in $WebEvent.Data) { $users += @{ Name = (New-Guid).Guid UserIdd = $id diff --git a/examples/web-route-endpoints.ps1 b/examples/web-route-endpoints.ps1 index 9016fb680..b8e40fc80 100644 --- a/examples/web-route-endpoints.ps1 +++ b/examples/web-route-endpoints.ps1 @@ -26,8 +26,7 @@ Start-PodeServer { # GET request with parameters Add-PodeRoute -Method Get -Path '/:userId/details' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ 'userId' = $e.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ 'userId' = $WebEvent.Parameters['userId'] } } # ALL requests for 127.0.0.2 to 127.0.0.1 diff --git a/examples/web-route-listen-names.ps1 b/examples/web-route-listen-names.ps1 index b2cb0204e..d15eabb9b 100644 --- a/examples/web-route-listen-names.ps1 +++ b/examples/web-route-listen-names.ps1 @@ -38,8 +38,7 @@ Start-PodeServer { # GET request with parameters Add-PodeRoute -Method Get -Path '/:userId/details' -ScriptBlock { - param($event) - Write-PodeJsonResponse -Value @{ 'userId' = $event.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ 'userId' = $WebEvent.Parameters['userId'] } } } \ No newline at end of file diff --git a/examples/web-route-protocols.ps1 b/examples/web-route-protocols.ps1 index 1f6957ee2..02998df07 100644 --- a/examples/web-route-protocols.ps1 +++ b/examples/web-route-protocols.ps1 @@ -26,8 +26,7 @@ Start-PodeServer { # GET request with parameters Add-PodeRoute -Method Get -Path '/:userId/details' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ 'userId' = $e.Parameters['userId'] } + Write-PodeJsonResponse -Value @{ 'userId' = $WebEvent.Parameters['userId'] } } # ALL requests for http only to redirect to https diff --git a/examples/web-sessions.ps1 b/examples/web-sessions.ps1 index 30c0538a9..cd408110e 100644 --- a/examples/web-sessions.ps1 +++ b/examples/web-sessions.ps1 @@ -20,9 +20,8 @@ Start-PodeServer { # GET request for web page on "localhost:8085/" Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($s) - $s.Session.Data.Views++ - Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @($s.Session.Data.Views); } + $WebEvent.Session.Data.Views++ + Write-PodeViewResponse -Path 'simple' -Data @{ 'numbers' = @($WebEvent.Session.Data.Views); } } } \ No newline at end of file diff --git a/src/Misc/default-swagger.html.pode b/src/Misc/default-swagger.html.pode index b67997765..bbe79f56f 100644 --- a/src/Misc/default-swagger.html.pode +++ b/src/Misc/default-swagger.html.pode @@ -26,6 +26,7 @@ .swagger-ui .parameter__type, .swagger-ui .parameter__deprecated, .swagger-ui .parameter__in, + .swagger-ui .parameter__enum, .swagger-ui table thead tr th, .swagger-ui .response-col_status, .swagger-ui .response-col_description, diff --git a/src/Private/Authentication.ps1 b/src/Private/Authentication.ps1 index f87578f54..ae2c01d2f 100644 --- a/src/Private/Authentication.ps1 +++ b/src/Private/Authentication.ps1 @@ -1,7 +1,7 @@ function Get-PodeAuthBasicType { return { - param($e, $options) + param($options) # get the auth header $header = (Get-PodeHeader -Name 'Authorization') @@ -62,8 +62,8 @@ function Get-PodeAuthBasicType function Get-PodeAuthClientCertificateType { return { - param($e, $options) - $cert = $e.Request.ClientCertificate + param($options) + $cert = $WebEvent.Request.ClientCertificate # ensure we have a client cert if ($null -eq $cert) { @@ -91,14 +91,14 @@ function Get-PodeAuthClientCertificateType } # return data for calling validator - return @($cert, $e.Request.ClientCertificateErrors) + return @($cert, $WebEvent.Request.ClientCertificateErrors) } } function Get-PodeAuthBearerType { return { - param($e, $options) + param($options) # get the auth header $header = (Get-PodeHeader -Name 'Authorization') @@ -136,7 +136,7 @@ function Get-PodeAuthBearerType function Get-PodeAuthBearerPostValidator { return { - param($e, $token, $result, $options) + param($token, $result, $options) # if there's no user, fail with challenge if (($null -eq $result) -or ($null -eq $result.User)) { @@ -219,7 +219,7 @@ function New-PodeAuthBearerChallenge function Get-PodeAuthDigestType { return { - param($e, $options) + param($options) # get the auth header - send challenge if missing $header = (Get-PodeHeader -Name 'Authorization') @@ -267,7 +267,7 @@ function Get-PodeAuthDigestType } # return 400 if domain doesnt match request domain - if ($e.Path -ine $params.uri) { + if ($WebEvent.Path -ine $params.uri) { return @{ Message = 'Invalid Authorization header' Code = 400 @@ -282,7 +282,7 @@ function Get-PodeAuthDigestType function Get-PodeAuthDigestPostValidator { return { - param($e, $username, $params, $result, $options) + param($username, $params, $result, $options) # if there's no user or password, fail with challenge if (($null -eq $result) -or ($null -eq $result.User) -or [string]::IsNullOrWhiteSpace($result.Password)) { @@ -297,7 +297,7 @@ function Get-PodeAuthDigestPostValidator $hash1 = Invoke-PodeMD5Hash -Value "$($params.username):$($params.realm):$($result.Password)" # generate the second hash - $hash2 = Invoke-PodeMD5Hash -Value "$($e.Method.ToUpperInvariant()):$($params.uri)" + $hash2 = Invoke-PodeMD5Hash -Value "$($WebEvent.Method.ToUpperInvariant()):$($params.uri)" # generate final hash $final = Invoke-PodeMD5Hash -Value "$($hash1):$($params.nonce):$($params.nc):$($params.cnonce):$($params.qop):$($hash2)" @@ -350,15 +350,15 @@ function New-PodeAuthDigestChallenge function Get-PodeAuthFormType { return { - param($e, $options) + param($options) # get user/pass keys to get from payload $userField = $options.Fields.Username $passField = $options.Fields.Password # get the user/pass - $username = $e.Data.$userField - $password = $e.Data.$passField + $username = $WebEvent.Data.$userField + $password = $WebEvent.Data.$passField # if either are empty, fail auth if ([string]::IsNullOrWhiteSpace($username) -or [string]::IsNullOrWhiteSpace($password)) { @@ -629,40 +629,40 @@ function Test-PodeAuthUserGroups function Get-PodeAuthMiddlewareScript { return { - param($e, $opts) + param($opts) # get the auth method $auth = Find-PodeAuth -Name $opts.Name # route options for using sessions $sessionless = $auth.Sessionless - $usingSessions = (!(Test-PodeIsEmpty $e.Session)) - $useHeaders = [bool]($e.Session.Properties.UseHeaders) + $usingSessions = (!(Test-PodeIsEmpty $WebEvent.Session)) + $useHeaders = [bool]($WebEvent.Session.Properties.UseHeaders) $loginRoute = $opts.Login # check for logout command if ($opts.Logout) { - Remove-PodeAuthSession -Event $e + Remove-PodeAuthSession if ($useHeaders) { return (Set-PodeAuthStatus -StatusCode 401 -Sessionless:$sessionless) } else { - $auth.Failure.Url = (Protect-PodeValue -Value $auth.Failure.Url -Default $e.Request.Url.AbsolutePath) + $auth.Failure.Url = (Protect-PodeValue -Value $auth.Failure.Url -Default $WebEvent.Request.Url.AbsolutePath) return (Set-PodeAuthStatus -StatusCode 302 -Failure $auth.Failure -Sessionless:$sessionless) } } # if the session already has a user/isAuth'd, then skip auth - if ($usingSessions -and !(Test-PodeIsEmpty $e.Session.Data.Auth.User) -and $e.Session.Data.Auth.IsAuthenticated) { - $e.Auth = $e.Session.Data.Auth + if ($usingSessions -and !(Test-PodeIsEmpty $WebEvent.Session.Data.Auth.User) -and $WebEvent.Session.Data.Auth.IsAuthenticated) { + $WebEvent.Auth = $WebEvent.Session.Data.Auth return (Set-PodeAuthStatus -Success $auth.Success -LoginRoute:$loginRoute -Sessionless:$sessionless) } # check if the login flag is set, in which case just return and load a login get-page - if ($loginRoute -and !$useHeaders -and ($e.Method -ieq 'get')) { - if (!(Test-PodeIsEmpty $e.Session.Data.Auth)) { - Revoke-PodeSession -Session $e.Session + if ($loginRoute -and !$useHeaders -and ($WebEvent.Method -ieq 'get')) { + if (!(Test-PodeIsEmpty $WebEvent.Session.Data.Auth)) { + Revoke-PodeSession -Session $WebEvent.Session } return $true @@ -670,7 +670,7 @@ function Get-PodeAuthMiddlewareScript try { # run auth scheme script to parse request for data - $_args = @($e) + @($auth.Scheme.Arguments) + $_args = @($auth.Scheme.Arguments) if ($null -ne $auth.Scheme.ScriptBlock.UsingVariables) { $_args = @($auth.Scheme.ScriptBlock.UsingVariables.Value) + $_args } @@ -682,10 +682,6 @@ function Get-PodeAuthMiddlewareScript $original = $result $_args = @($result) + @($auth.Arguments) - if ($auth.PassEvent) { - $_args = @($e) + $_args - } - if ($null -ne $auth.UsingVariables) { $_args = @($auth.UsingVariables.Value) + $_args } @@ -694,7 +690,7 @@ function Get-PodeAuthMiddlewareScript # if we have user, then run post validator if present if ([string]::IsNullOrWhiteSpace($result.Code) -and !(Test-PodeIsEmpty $auth.Scheme.PostValidator.Script)) { - $_args = @($e) + @($original) + @($result) + @($auth.Scheme.Arguments) + $_args = @($original) + @($result) + @($auth.Scheme.Arguments) if ($null -ne $auth.Scheme.PostValidator.UsingVariables) { $_args = @($auth.Scheme.PostValidator.UsingVariables.Value) + $_args } @@ -734,10 +730,10 @@ function Get-PodeAuthMiddlewareScript } # assign the user to the session, and wire up a quick method - $e.Auth = @{} - $e.Auth.User = $result.User - $e.Auth.IsAuthenticated = $true - $e.Auth.Store = !$sessionless + $WebEvent.Auth = @{} + $WebEvent.Auth.User = $result.User + $WebEvent.Auth.IsAuthenticated = $true + $WebEvent.Auth.Store = !$sessionless # continue return (Set-PodeAuthStatus -Headers $result.Headers -Success $auth.Success -LoginRoute:$loginRoute -Sessionless:$sessionless) @@ -778,22 +774,16 @@ function Get-PodeAuthWwwHeaderValue function Remove-PodeAuthSession { - param ( - [Parameter(Mandatory=$true)] - [ValidateNotNull()] - $Event - ) - # blank out the auth - $Event.Auth = @{} + $WebEvent.Auth = @{} # if a session auth is found, blank it - if (!(Test-PodeIsEmpty $Event.Session.Data.Auth)) { - $Event.Session.Data.Remove('Auth') + if (!(Test-PodeIsEmpty $WebEvent.Session.Data.Auth)) { + $WebEvent.Session.Data.Remove('Auth') } # Delete the session (remove from store, blank it, and remove from Response) - Revoke-PodeSession -Session $Event.Session + Revoke-PodeSession -Session $WebEvent.Session } function Set-PodeAuthStatus diff --git a/src/Private/Endware.ps1 b/src/Private/Endware.ps1 index 3661f53ad..b155cea5b 100644 --- a/src/Private/Endware.ps1 +++ b/src/Private/Endware.ps1 @@ -22,7 +22,7 @@ function Invoke-PodeEndware } try { - $_args = @($WebEvent) + @($eware.Arguments) + $_args = @($eware.Arguments) if ($null -ne $eware.UsingVariables) { $_args = @($eware.UsingVariables.Value) + $_args } diff --git a/src/Private/Logging.ps1 b/src/Private/Logging.ps1 index 11d0dd9f4..dc59de6f8 100644 --- a/src/Private/Logging.ps1 +++ b/src/Private/Logging.ps1 @@ -257,8 +257,7 @@ function Add-PodeRequestLogEndware # add the request logging endware $WebEvent.OnEnd += @{ Logic = { - param($e) - Write-PodeRequestLog -Request $e.Request -Response $e.Response -Path $e.Path + Write-PodeRequestLog -Request $WebEvent.Request -Response $WebEvent.Response -Path $WebEvent.Path } } } @@ -298,6 +297,7 @@ function Start-PodeLoggingRunspace } # convert to log item into a writable format + #TODO: "$LogItem" ? $_args = @($log.Item) + @($logger.Arguments) if ($null -ne $logger.UsingVariables) { $_args = @($logger.UsingVariables.Value) + $_args @@ -326,6 +326,7 @@ function Start-PodeLoggingRunspace # send the writable log item off to the log writer if ($null -ne $result) { + #TODO: "$LogItem" ? $_args = @(,$result) + @($logger.Method.Arguments) if ($null -ne $logger.Method.UsingVariables) { $_args = @($logger.Method.UsingVariables.Value) + $_args @@ -356,6 +357,7 @@ function Test-PodeLoggerBatches $result = $batch.Items $batch.Items = @() + #TODO: "$LogItem" ? $_args = @(,$result) + @($logger.Method.Arguments) if ($null -ne $logger.Method.UsingVariables) { $_args = @($logger.Method.UsingVariables.Value) + $_args diff --git a/src/Private/Middleware.ps1 b/src/Private/Middleware.ps1 index d8b9c9482..ded6e0132 100644 --- a/src/Private/Middleware.ps1 +++ b/src/Private/Middleware.ps1 @@ -43,7 +43,7 @@ function Invoke-PodeMiddleware } try { - $_args = @($WebEvent) + @($midware.Arguments) + $_args = @($midware.Arguments) if ($null -ne $midware.UsingVariables) { $_args = @($midware.UsingVariables.Value) + $_args } @@ -140,15 +140,13 @@ function Get-PodeInbuiltMiddleware function Get-PodeAccessMiddleware { return (Get-PodeInbuiltMiddleware -Name '__pode_mw_access__' -ScriptBlock { - param($e) - # are there any rules? if (($PodeContext.Server.Access.Allow.Count -eq 0) -and ($PodeContext.Server.Access.Deny.Count -eq 0)) { return $true } # ensure the request IP address is allowed - if (!(Test-PodeIPAccess -IP $e.Request.RemoteEndPoint.Address)) { + if (!(Test-PodeIPAccess -IP $WebEvent.Request.RemoteEndPoint.Address)) { Set-PodeResponseStatus -Code 403 return $false } @@ -161,27 +159,25 @@ function Get-PodeAccessMiddleware function Get-PodeLimitMiddleware { return (Get-PodeInbuiltMiddleware -Name '__pode_mw_rate_limit__' -ScriptBlock { - param($e) - # are there any rules? if ($PodeContext.Server.Limits.Rules.Count -eq 0) { return $true } # check the request IP address has not hit a rate limit - if (!(Test-PodeIPLimit -IP $e.Request.RemoteEndPoint.Address)) { + if (!(Test-PodeIPLimit -IP $WebEvent.Request.RemoteEndPoint.Address)) { Set-PodeResponseStatus -Code 429 return $false } # check the route - if (!(Test-PodeRouteLimit -Path $e.Path)) { + if (!(Test-PodeRouteLimit -Path $WebEvent.Path)) { Set-PodeResponseStatus -Code 429 return $false } # check the endpoint - if (!(Test-PodeEndpointLimit -EndpointName $e.Endpoint.Name)) { + if (!(Test-PodeEndpointLimit -EndpointName $WebEvent.Endpoint.Name)) { Set-PodeResponseStatus -Code 429 return $false } @@ -194,16 +190,14 @@ function Get-PodeLimitMiddleware function Get-PodePublicMiddleware { return (Get-PodeInbuiltMiddleware -Name '__pode_mw_static_content__' -ScriptBlock { - param($e) - # only find public static content here - $path = Find-PodePublicRoute -Path $e.Path + $path = Find-PodePublicRoute -Path $WebEvent.Path if ([string]::IsNullOrWhiteSpace($path)) { return $true } # check current state of caching - $cachable = Test-PodeRouteValidForCaching -Path $e.Path + $cachable = Test-PodeRouteValidForCaching -Path $WebEvent.Path # write the file to the response Write-PodeFileResponse -Path $path -MaxAge $PodeContext.Server.Web.Static.Cache.MaxAge -Cache:$cachable @@ -218,12 +212,10 @@ function Get-PodeRouteValidateMiddleware return @{ Name = '__pode_mw_route_validation__' Logic = { - param($e) - # check if the path is static route first, then check the main routes - $route = Find-PodeStaticRoute -Path $e.Path -EndpointName $e.Endpoint.Name + $route = Find-PodeStaticRoute -Path $WebEvent.Path -EndpointName $WebEvent.Endpoint.Name if ($null -eq $route) { - $route = Find-PodeRoute -Method $e.Method -Path $e.Path -EndpointName $e.Endpoint.Name -CheckWildMethod + $route = Find-PodeRoute -Method $WebEvent.Method -Path $WebEvent.Path -EndpointName $WebEvent.Endpoint.Name -CheckWildMethod } # if there's no route defined, it's a 404 - or a 405 if a route exists for any other method @@ -231,7 +223,7 @@ function Get-PodeRouteValidateMiddleware # check if a route exists for another method $methods = @('DELETE', 'GET', 'HEAD', 'MERGE', 'OPTIONS', 'PATCH', 'POST', 'PUT', 'TRACE') $diff_route = @(foreach ($method in $methods) { - $r = Find-PodeRoute -Method $method -Path $e.Path -EndpointName $e.Endpoint.Name + $r = Find-PodeRoute -Method $method -Path $WebEvent.Path -EndpointName $WebEvent.Endpoint.Name if ($null -ne $r) { $r break @@ -250,31 +242,31 @@ function Get-PodeRouteValidateMiddleware # check if static and split if ($null -ne $route.Content) { - $e.StaticContent = $route.Content + $WebEvent.StaticContent = $route.Content $route = $route.Route } # set the route parameters - $e.Parameters = @{} - if ($e.Path -imatch "$($route.Path)$") { - $e.Parameters = $Matches + $WebEvent.Parameters = @{} + if ($WebEvent.Path -imatch "$($route.Path)$") { + $WebEvent.Parameters = $Matches } # set the route on the WebEvent - $e.Route = $route + $WebEvent.Route = $route # override the content type from the route if it's not empty if (![string]::IsNullOrWhiteSpace($route.ContentType)) { - $e.ContentType = $route.ContentType + $WebEvent.ContentType = $route.ContentType } # override the transfer encoding from the route if it's not empty if (![string]::IsNullOrWhiteSpace($route.TransferEncoding)) { - $e.TransferEncoding = $route.TransferEncoding + $WebEvent.TransferEncoding = $route.TransferEncoding } # set the content type for any pages for the route if it's not empty - $e.ErrorType = $route.ErrorType + $WebEvent.ErrorType = $route.ErrorType # route exists return $true @@ -285,15 +277,13 @@ function Get-PodeRouteValidateMiddleware function Get-PodeBodyMiddleware { return (Get-PodeInbuiltMiddleware -Name '__pode_mw_body_parsing__' -ScriptBlock { - param($e) - try { # attempt to parse that data - $result = ConvertFrom-PodeRequestContent -Request $e.Request -ContentType $e.ContentType -TransferEncoding $e.TransferEncoding + $result = ConvertFrom-PodeRequestContent -Request $WebEvent.Request -ContentType $WebEvent.ContentType -TransferEncoding $WebEvent.TransferEncoding # set session data - $e.Data = $result.Data - $e.Files = $result.Files + $WebEvent.Data = $result.Data + $WebEvent.Files = $result.Files # payload parsed return $true @@ -308,11 +298,9 @@ function Get-PodeBodyMiddleware function Get-PodeQueryMiddleware { return (Get-PodeInbuiltMiddleware -Name '__pode_mw_query_parsing__' -ScriptBlock { - param($e) - try { # set the query string from the request - $e.Query = (ConvertFrom-PodeNameValueToHashTable -Collection $e.Request.QueryString) + $WebEvent.Query = (ConvertFrom-PodeNameValueToHashTable -Collection $WebEvent.Request.QueryString) return $true } catch { @@ -325,10 +313,8 @@ function Get-PodeQueryMiddleware function Get-PodeCookieMiddleware { return (Get-PodeInbuiltMiddleware -Name '__pode_mw_cookie_parsing__' -ScriptBlock { - param($e) - # if cookies already set, return - if ($e.Cookies.Count -gt 0) { + if ($WebEvent.Cookies.Count -gt 0) { return $true } @@ -340,7 +326,7 @@ function Get-PodeCookieMiddleware # parse the cookies from the header $cookies = @($h_cookie -split '; ') - $e.Cookies = @{} + $WebEvent.Cookies = @{} foreach ($cookie in $cookies) { $atoms = $cookie.Split('=', 2) @@ -352,7 +338,7 @@ function Get-PodeCookieMiddleware } } - $e.Cookies[$atoms[0]] = [System.Net.Cookie]::new($atoms[0], $value) + $WebEvent.Cookies[$atoms[0]] = [System.Net.Cookie]::new($atoms[0], $value) } return $true diff --git a/src/Private/PodeServer.ps1 b/src/Private/PodeServer.ps1 index 12d297831..280fd3308 100644 --- a/src/Private/PodeServer.ps1 +++ b/src/Private/PodeServer.ps1 @@ -155,7 +155,7 @@ function Start-PodeWebServer } } elseif ($null -ne $WebEvent.Route.Logic) { - $_args = @($WebEvent) + @($WebEvent.Route.Arguments) + $_args = @($WebEvent.Route.Arguments) if ($null -ne $WebEvent.Route.UsingVariables) { $_args = @($WebEvent.Route.UsingVariables.Value) + $_args } diff --git a/src/Private/Serverless.ps1 b/src/Private/Serverless.ps1 index 82edaa71e..f82979f7e 100644 --- a/src/Private/Serverless.ps1 +++ b/src/Private/Serverless.ps1 @@ -79,7 +79,7 @@ function Start-PodeAzFuncServer # invoke the route if ($null -ne $WebEvent.StaticContent) { if ($WebEvent.StaticContent.IsDownload) { - Set-PodeResponseAttachment -Path $e.Path + Set-PodeResponseAttachment -Path $WebEvent.Path } else { $cachable = $WebEvent.StaticContent.IsCachable @@ -182,7 +182,7 @@ function Start-PodeAwsLambdaServer # invoke the route if ($null -ne $WebEvent.StaticContent) { if ($WebEvent.StaticContent.IsDownload) { - Set-PodeResponseAttachment -Path $e.Path + Set-PodeResponseAttachment -Path $WebEvent.Path } else { $cachable = $WebEvent.StaticContent.IsCachable diff --git a/src/Private/ServiceServer.ps1 b/src/Private/ServiceServer.ps1 index a681739c4..66c2196bd 100644 --- a/src/Private/ServiceServer.ps1 +++ b/src/Private/ServiceServer.ps1 @@ -24,6 +24,7 @@ function Start-PodeServiceServer foreach ($name in $handlers.Keys) { $handler = $handlers[$name] + #TODO: Remove $ServiceEvent from args $_args = @($ServiceEvent) + @($handler.Arguments) if ($null -ne $handler.UsingVariables) { $_args = @($handler.UsingVariables.Value) + $_args diff --git a/src/Private/Sessions.ps1 b/src/Private/Sessions.ps1 index acbd21441..2e71c6c0b 100644 --- a/src/Private/Sessions.ps1 +++ b/src/Private/Sessions.ps1 @@ -340,7 +340,7 @@ function Get-PodeSessionData ) if ($PodeContext.Server.Sessions.Store.Get -is [psscriptmethod]) { - return $PodeContext.Server.Sessions.Store.Get($e.Session.Id) + return $PodeContext.Server.Sessions.Store.Get($WebEvent.Session.Id) } else { return (Invoke-PodeScriptBlock -ScriptBlock $PodeContext.Server.Sessions.Store.Get -Arguments $SessionId -Return) @@ -350,46 +350,44 @@ function Get-PodeSessionData function Get-PodeSessionMiddleware { return { - param($e) - # if session already set, return - if ($e.Session) { + if ($WebEvent.Session) { return $true } try { # get the session from cookie/header - $e.Session = Get-PodeSession -Session $PodeContext.Server.Sessions + $WebEvent.Session = Get-PodeSession -Session $PodeContext.Server.Sessions # if no session found, create a new one on the current web event - if (!$e.Session) { - $e.Session = (New-PodeSession) + if (!$WebEvent.Session) { + $WebEvent.Session = (New-PodeSession) $new = $true } # get the session's data - elseif ($null -ne ($data = (Get-PodeSessionData -SessionId $e.Session.Id))) { - $e.Session.Data = $data - Set-PodeSessionDataHash -Session $e.Session + elseif ($null -ne ($data = (Get-PodeSessionData -SessionId $WebEvent.Session.Id))) { + $WebEvent.Session.Data = $data + Set-PodeSessionDataHash -Session $WebEvent.Session } # session not in store, create a new one else { - $e.Session = (New-PodeSession) + $WebEvent.Session = (New-PodeSession) $new = $true } # add helper methods to session - Set-PodeSessionHelpers -Session $e.Session + Set-PodeSessionHelpers -Session $WebEvent.Session # add session to response if it's new or extendible - if ($new -or $e.Session.Properties.Extend) { - Set-PodeSession -Session $e.Session + if ($new -or $WebEvent.Session.Properties.Extend) { + Set-PodeSession -Session $WebEvent.Session } # assign endware for session to set cookie/header - $e.OnEnd += @{ + $WebEvent.OnEnd += @{ Logic = { Save-PodeSession -Force } diff --git a/src/Private/SmtpServer.ps1 b/src/Private/SmtpServer.ps1 index cca9a004c..5d49c704f 100644 --- a/src/Private/SmtpServer.ps1 +++ b/src/Private/SmtpServer.ps1 @@ -64,7 +64,7 @@ function Start-PodeSmtpServer $Request = $context.Request $Response = $context.Response - $TcpEvent = @{ + $SmtpEvent = @{ Response = $Response Request = $Request Lockable = $PodeContext.Lockable @@ -100,7 +100,7 @@ function Start-PodeSmtpServer foreach ($name in $handlers.Keys) { $handler = $handlers[$name] - $_args = @($TcpEvent) + @($handler.Arguments) + $_args = @($handler.Arguments) if ($null -ne $handler.UsingVariables) { $_args = @($handler.UsingVariables.Value) + $_args } diff --git a/src/Private/TcpServer.ps1 b/src/Private/TcpServer.ps1 index 06862293f..ff75d801b 100644 --- a/src/Private/TcpServer.ps1 +++ b/src/Private/TcpServer.ps1 @@ -69,7 +69,7 @@ function Start-PodeTcpServer foreach ($name in $handlers.Keys) { $handler = $handlers[$name] - $_args = @($TcpEvent) + @($handler.Arguments) + $_args = @($handler.Arguments) if ($null -ne $handler.UsingVariables) { $_args = @($handler.UsingVariables.Value) + $_args } diff --git a/src/Private/Timers.ps1 b/src/Private/Timers.ps1 index fd5084a3b..609c87b67 100644 --- a/src/Private/Timers.ps1 +++ b/src/Private/Timers.ps1 @@ -60,9 +60,9 @@ function Invoke-PodeInternalTimer ) try { - $_event = @{ Lockable = $PodeContext.Lockable } + $TimerEvent = @{ Lockable = $PodeContext.Lockable } - $_args = @($_event) + @($Timer.Arguments) + $_args = @($Timer.Arguments) if ($null -ne $Timer.UsingVariables) { $_args = @($Timer.UsingVariables.Value) + $_args } diff --git a/src/Public/Authentication.ps1 b/src/Public/Authentication.ps1 index 83a6a36d0..7f45c0bc0 100644 --- a/src/Public/Authentication.ps1 +++ b/src/Public/Authentication.ps1 @@ -294,9 +294,6 @@ The URL to redirect to when authentication succeeds when logging in. .PARAMETER Sessionless If supplied, authenticated users will not be stored in sessions, and sessions will not be used. -.PARAMETER PassEvent -If supplied, the current web event will be supplied as the first parameter to the ScriptBlock. - .EXAMPLE New-PodeAuthScheme -Form | Add-PodeAuth -Name 'Main' -ScriptBlock { /* logic */ } #> @@ -340,10 +337,7 @@ function Add-PodeAuth $SuccessUrl, [switch] - $Sessionless, - - [switch] - $PassEvent + $Sessionless ) # ensure the name doesn't already exist @@ -371,7 +365,6 @@ function Add-PodeAuth UsingVariables = $usingVars Arguments = $ArgumentList Sessionless = $Sessionless - PassEvent = $PassEvent Failure = @{ Url = $FailureUrl Message = $FailureMessage @@ -729,7 +722,7 @@ function Add-PodeAuthIIS # create the auth scheme for getting the token header $scheme = New-PodeAuthScheme -Custom -ScriptBlock { - param($e, $options) + param($options) $header = 'MS-ASPNETCORE-WINAUTHTOKEN' diff --git a/src/Public/Core.ps1 b/src/Public/Core.ps1 index a0c8de8b9..6150df643 100644 --- a/src/Public/Core.ps1 +++ b/src/Public/Core.ps1 @@ -933,7 +933,7 @@ function Add-PodeEndpoint # build the redirect route Add-PodeRoute -Method * -Path * -EndpointName $obj.Name -ArgumentList $redir_endpoint -ScriptBlock { - param($e, $endpoint) + param($endpoint) Move-PodeResponseUrl -EndpointName $endpoint.Name } } diff --git a/src/Public/Middleware.ps1 b/src/Public/Middleware.ps1 index 289cd400e..71dc0fb83 100644 --- a/src/Public/Middleware.ps1 +++ b/src/Public/Middleware.ps1 @@ -295,7 +295,7 @@ function Remove-PodeSession } # remove the session, and from auth and cookies - Remove-PodeAuthSession -Event $WebEvent + Remove-PodeAuthSession } <# @@ -437,8 +437,6 @@ function Get-PodeCsrfMiddleware # return scriptblock for the csrf route middleware to test tokens $script = { - param($e) - # if there's not a secret, generate and store it $secret = New-PodeCsrfSecret @@ -568,11 +566,9 @@ function Enable-PodeCsrfMiddleware # return scriptblock for the csrf middleware $script = { - param($e) - # if the current route method is ignored, just return $ignored = @($PodeContext.Server.Cookies.Csrf.IgnoredMethods) - if (!(Test-PodeIsEmpty $ignored) -and ($ignored -icontains $e.Method)) { + if (!(Test-PodeIsEmpty $ignored) -and ($ignored -icontains $WebEvent.Method)) { return $true } diff --git a/src/Public/OpenApi.ps1 b/src/Public/OpenApi.ps1 index 1ee344933..cd7ba2ddc 100644 --- a/src/Public/OpenApi.ps1 +++ b/src/Public/OpenApi.ps1 @@ -83,7 +83,7 @@ function Enable-PodeOpenApi # add the OpenAPI route Add-PodeRoute -Method Get -Path $Path -ArgumentList $meta -Middleware $Middleware -ScriptBlock { - param($e, $meta) + param($meta) $strict = $meta.RestrictRoutes # generate the openapi definition @@ -92,9 +92,9 @@ function Enable-PodeOpenApi -Version $meta.Version ` -Description $meta.Description ` -RouteFilter $meta.RouteFilter ` - -Protocol $e.Endpoint.Protocol ` - -Address $e.Endpoint.Address ` - -EndpointName $e.Endpoint.Name ` + -Protocol $WebEvent.Endpoint.Protocol ` + -Address $WebEvent.Endpoint.Address ` + -EndpointName $WebEvent.Endpoint.Name ` -RestrictRoutes:$strict # write the openapi definition @@ -1448,7 +1448,7 @@ function Enable-PodeOpenApiViewer # add the viewer route Add-PodeRoute -Method Get -Path $Path -Middleware $Middleware -ArgumentList $meta -ScriptBlock { - param($e, $meta) + param($meta) $podeRoot = Get-PodeModuleMiscPath Write-PodeFileResponse -Path (Join-Path $podeRoot "default-$($meta.Type).html.pode") -Data @{ Title = $meta.Title diff --git a/src/Public/Routes.ps1 b/src/Public/Routes.ps1 index 8b218c8ab..2f9e1df5a 100644 --- a/src/Public/Routes.ps1 +++ b/src/Public/Routes.ps1 @@ -748,14 +748,14 @@ function ConvertTo-PodeRoute # create the route $route = (Add-PodeRoute -Method $_method -Path $_path -Middleware $Middleware -Authentication $Authentication -ArgumentList $cmd -ScriptBlock { - param($e, $cmd) + param($cmd) # either get params from the QueryString or Payload - if ($e.Method -ieq 'get') { - $parameters = $e.Query + if ($WebEvent.Method -ieq 'get') { + $parameters = $WebEvent.Query } else { - $parameters = $e.Data + $parameters = $WebEvent.Data } # invoke the function @@ -906,7 +906,7 @@ function Add-PodePage $arg = @($ScriptBlock, $Data) $logic = { - param($e, $script, $data) + param($script, $data) # invoke the function (optional splat data) if (Test-PodeIsEmpty $data) { @@ -927,7 +927,7 @@ function Add-PodePage $FilePath = Get-PodeRelativePath -Path $FilePath -JoinRoot -TestPath $arg = @($FilePath, $Data) $logic = { - param($e, $file, $data) + param($file, $data) Write-PodeFileResponse -Path $file -ContentType 'text/html' -Data $data } } @@ -935,7 +935,7 @@ function Add-PodePage 'view' { $arg = @($View, $Data, $FlashMessages) $logic = { - param($e, $view, $data, [bool]$flash) + param($view, $data, [bool]$flash) Write-PodeViewResponse -Path $view -Data $data -FlashMessages:$flash } } diff --git a/tests/integration/RestApi.Tests.ps1 b/tests/integration/RestApi.Tests.ps1 index e55d98ba2..3d679d7d3 100644 --- a/tests/integration/RestApi.Tests.ps1 +++ b/tests/integration/RestApi.Tests.ps1 @@ -28,23 +28,19 @@ Describe 'REST API Requests' { } Add-PodeRoute -Method Get -Path '/data/query' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Username = $e.Query.username } + Write-PodeJsonResponse -Value @{ Username = $WebEvent.Query.username } } Add-PodeRoute -Method Post -Path '/data/payload' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Username = $e.Data.username } + Write-PodeJsonResponse -Value @{ Username = $WebEvent.Data.username } } Add-PodeRoute -Method Post -Path '/data/payload-forced-type' -ContentType 'application/json' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Username = $e.Data.username } + Write-PodeJsonResponse -Value @{ Username = $WebEvent.Data.username } } Add-PodeRoute -Method Get -Path '/data/param/:username' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Username = $e.Parameters.username } + Write-PodeJsonResponse -Value @{ Username = $WebEvent.Parameters.username } } Add-PodeRoute -Method Get -Path '/data/param/:username/messages' -ScriptBlock { @@ -66,13 +62,11 @@ Describe 'REST API Requests' { } Add-PodeRoute -Method Post -Path '/encoding/transfer' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Username = $e.Data.username } + Write-PodeJsonResponse -Value @{ Username = $WebEvent.Data.username } } Add-PodeRoute -Method Post -Path '/encoding/transfer-forced-type' -TransferEncoding 'gzip' -ScriptBlock { - param($e) - Write-PodeJsonResponse -Value @{ Username = $e.Data.username } + Write-PodeJsonResponse -Value @{ Username = $WebEvent.Data.username } } Add-PodeRoute -Method * -Path '/all' -ScriptBlock { diff --git a/tests/integration/Sessions.Tests.ps1 b/tests/integration/Sessions.Tests.ps1 index b57e0e10c..bfa4dd6e1 100644 --- a/tests/integration/Sessions.Tests.ps1 +++ b/tests/integration/Sessions.Tests.ps1 @@ -26,13 +26,12 @@ Describe 'Session Requests' { } Add-PodeRoute -Method Post -Path '/auth/basic' -Authentication Auth -ScriptBlock { - param($e) - $e.Session.Data.Views++ + $WebEvent.Session.Data.Views++ Write-PodeJsonResponse -Value @{ Result = 'OK' - Username = $e.Auth.User.ID - Views = $e.Session.Data.Views + Username = $WebEvent.Auth.User.ID + Views = $WebEvent.Session.Data.Views } } } diff --git a/tests/unit/Authentication.Tests.ps1 b/tests/unit/Authentication.Tests.ps1 index 9888ad72c..31d891aac 100644 --- a/tests/unit/Authentication.Tests.ps1 +++ b/tests/unit/Authentication.Tests.ps1 @@ -69,7 +69,7 @@ Describe 'Remove-PodeAuthSession' { It 'Removes the user, and kills the session' { Mock Revoke-PodeSession {} - $event = @{ + $WebEvent = @{ Auth = @{ User = @{} } Session = @{ Data = @{ @@ -78,11 +78,11 @@ Describe 'Remove-PodeAuthSession' { } } - Remove-PodeAuthSession -Event $event + Remove-PodeAuthSession - $event.Auth.Count | Should Be 0 - $event.Auth.User | Should Be $null - $event.Session.Data.Auth | Should be $null + $WebEvent.Auth.Count | Should Be 0 + $WebEvent.Auth.User | Should Be $null + $WebEvent.Session.Data.Auth | Should be $null Assert-MockCalled Revoke-PodeSession -Times 1 -Scope It } @@ -90,7 +90,7 @@ Describe 'Remove-PodeAuthSession' { It 'Removes the user, and kills the session, redirecting to root' { Mock Revoke-PodeSession {} - $event = @{ + $WebEvent = @{ Auth = @{ User = @{} } Session = @{ Data = @{ @@ -102,11 +102,11 @@ Describe 'Remove-PodeAuthSession' { } } - Remove-PodeAuthSession -Event $event + Remove-PodeAuthSession - $event.Auth.Count | Should Be 0 - $event.Auth.User | Should Be $null - $event.Session.Data.Auth | Should be $null + $WebEvent.Auth.Count | Should Be 0 + $WebEvent.Auth.User | Should Be $null + $WebEvent.Session.Data.Auth | Should be $null Assert-MockCalled Revoke-PodeSession -Times 1 -Scope It } diff --git a/tests/unit/Middleware.Tests.ps1 b/tests/unit/Middleware.Tests.ps1 index 9c3297860..ca646b9a0 100644 --- a/tests/unit/Middleware.Tests.ps1 +++ b/tests/unit/Middleware.Tests.ps1 @@ -248,9 +248,12 @@ Describe 'Get-PodeAccessMiddleware' { $r.Logic | Should Not Be $null Mock Test-PodeIPAccess { return $true } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = @{ 'RemoteEndPoint' = @{ 'Address' = 'localhost' } } - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as true, no rule' { @@ -258,9 +261,11 @@ Describe 'Get-PodeAccessMiddleware' { $r.Name | Should Be '__pode_mw_access__' $r.Logic | Should Not Be $null - (. $r.Logic @{ + $WebEvent = @{ 'Request' = @{ 'RemoteEndPoint' = @{ 'Address' = 'localhost' } } - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as false' { @@ -278,9 +283,12 @@ Describe 'Get-PodeAccessMiddleware' { Mock Test-PodeIPAccess { return $false } Mock Set-PodeResponseStatus { } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = @{ 'RemoteEndPoint' = @{ 'Address' = 'localhost' } } - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false } } @@ -296,9 +304,12 @@ Describe 'Get-PodeLimitMiddleware' { $r.Logic | Should Not Be $null Mock Test-PodeIPLimit { return $true } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = @{ 'RemoteEndPoint' = @{ 'Address' = 'localhost' } } - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as true, no rules' { @@ -306,9 +317,11 @@ Describe 'Get-PodeLimitMiddleware' { $r.Name | Should Be '__pode_mw_rate_limit__' $r.Logic | Should Not Be $null - (. $r.Logic @{ + $WebEvent = @{ 'Request' = @{ 'RemoteEndPoint' = @{ 'Address' = 'localhost' } } - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as false' { @@ -326,9 +339,12 @@ Describe 'Get-PodeLimitMiddleware' { Mock Test-PodeIPLimit { return $false } Mock Set-PodeResponseStatus { } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = @{ 'RemoteEndPoint' = @{ 'Address' = 'localhost' } } - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false } } @@ -348,10 +364,12 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeStaticRoute { return $null } Mock Find-PodeRoute { return @{ 'Parameters' = @{}; 'Logic' = { Write-Host 'hello' }; } } - (. $r.Logic @{ + $WebEvent = @{ 'Method' = 'GET'; 'Path' = '/'; - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as true, overriding the content type' { @@ -373,7 +391,7 @@ Describe 'Get-PodeRouteValidateMiddleware' { 'ContentType' = 'application/json'; } } - (. $r.Logic $WebEvent) | Should Be $true + (. $r.Logic) | Should Be $true $WebEvent.Route | Should Not Be $null $WebEvent.ContentType | Should Be 'application/json' } @@ -387,10 +405,12 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeRoute { return $null } Mock Set-PodeResponseStatus { } - (. $r.Logic @{ + $WebEvent = @{ 'Method' = 'GET'; 'Path' = '/'; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false } It 'Returns a ScriptBlock, invokes false for no static path' { @@ -402,10 +422,12 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeRoute { return $null } Mock Set-PodeResponseStatus { } - (. $r.Logic @{ + $WebEvent = @{ 'Method' = 'GET'; 'Path' = '/'; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false } It 'Returns a ScriptBlock and invokes it as true, for static content' { @@ -423,7 +445,7 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeStaticRoute { return @{ Content = @{ Source = '/'; Download = $true }; Route = @{} } } Mock Find-PodeRoute { return $null } - (. $r.Logic $WebEvent) | Should Be $true + (. $r.Logic) | Should Be $true $WebEvent.Route | Should Not Be $null $WebEvent.StaticContent | Should Not Be $null $WebEvent.StaticContent.Download | Should Be $true @@ -452,7 +474,7 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeStaticRoute { return @{ Content = @{ Source = '/' }; Route = @{} } } Mock Find-PodeRoute { return $null } - (. $r.Logic $WebEvent) | Should Be $true + (. $r.Logic) | Should Be $true $WebEvent.Route | Should Not Be $null $WebEvent.StaticContent | Should Not Be $null } @@ -481,7 +503,7 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeStaticRoute { return @{ Content = @{ Source = '/' }; Route = @{} } } Mock Find-PodeRoute { return $null } - (. $r.Logic $WebEvent) | Should Be $true + (. $r.Logic) | Should Be $true $WebEvent.Route | Should Not Be $null $WebEvent.StaticContent | Should Not Be $null } @@ -510,7 +532,7 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeStaticRoute { return @{ Content = @{ Source = '/' }; Route = @{} } } Mock Find-PodeRoute { return $null } - (. $r.Logic $WebEvent) | Should Be $true + (. $r.Logic) | Should Be $true $WebEvent.Route | Should Not Be $null $WebEvent.StaticContent | Should Not Be $null } @@ -538,7 +560,7 @@ Describe 'Get-PodeRouteValidateMiddleware' { Mock Find-PodeStaticRoute { return @{ Content = @{ Source = '/' }; Route = @{} } } Mock Find-PodeRoute { return $null } - (. $r.Logic $WebEvent) | Should Be $true + (. $r.Logic) | Should Be $true $WebEvent.Route | Should Not Be $null $WebEvent.StaticContent | Should Not Be $null } @@ -556,9 +578,12 @@ Describe 'Get-PodeBodyMiddleware' { $r.Logic | Should Not Be $null Mock ConvertFrom-PodeRequestContent { return @{ 'Data' = @{}; 'Files' = @{}; } } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = 'value' - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as false' { @@ -568,9 +593,12 @@ Describe 'Get-PodeBodyMiddleware' { Mock ConvertFrom-PodeRequestContent { throw 'error' } Mock Set-PodeResponseStatus { } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = 'value' - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false } } @@ -586,9 +614,12 @@ Describe 'Get-PodeQueryMiddleware' { $r.Logic | Should Not Be $null Mock ConvertFrom-PodeNameValueToHashTable { return 'string' } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = @{ 'QueryString' = [System.Web.HttpUtility]::ParseQueryString('name=bob') } - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock and invokes it as false' { @@ -598,9 +629,12 @@ Describe 'Get-PodeQueryMiddleware' { Mock ConvertFrom-PodeNameValueToHashTable { throw 'error' } Mock Set-PodeResponseStatus { } - (. $r.Logic @{ + + $WebEvent = @{ 'Request' = @{ 'QueryString' = 'name=bob' } - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false } } @@ -616,9 +650,12 @@ Describe 'Get-PodePublicMiddleware' { $r.Logic | Should Not Be $null Mock Find-PodePublicRoute { return $null } - (. $r.Logic @{ + + $WebEvent = @{ 'Path' = '/'; 'Protocol' = 'http'; 'Endpoint' = ''; - }) | Should Be $true + } + + (. $r.Logic) | Should Be $true } It 'Returns a ScriptBlock, invokes false for static path' { @@ -633,9 +670,11 @@ Describe 'Get-PodePublicMiddleware' { Mock Find-PodePublicRoute { return '/' } Mock Write-PodeFileResponse { } - (. $r.Logic @{ + $WebEvent = @{ 'Path' = '/'; 'Protocol' = 'http'; 'Endpoint' = ''; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false Assert-MockCalled Write-PodeFileResponse -Times 1 -Scope It } @@ -656,9 +695,11 @@ Describe 'Get-PodePublicMiddleware' { Mock Find-PodePublicRoute { return '/' } Mock Write-PodeFileResponse { } - (. $r.Logic @{ + $WebEvent = @{ 'Path' = '/'; 'Protocol' = 'http'; 'Endpoint' = ''; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false Assert-MockCalled Write-PodeFileResponse -Times 1 -Scope It } @@ -680,9 +721,11 @@ Describe 'Get-PodePublicMiddleware' { Mock Find-PodePublicRoute { return '/' } Mock Write-PodeFileResponse { } - (. $r.Logic @{ + $WebEvent = @{ 'Path' = '/'; 'Protocol' = 'http'; 'Endpoint' = ''; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false Assert-MockCalled Write-PodeFileResponse -Times 1 -Scope It } @@ -704,9 +747,11 @@ Describe 'Get-PodePublicMiddleware' { Mock Find-PodePublicRoute { return '/' } Mock Write-PodeFileResponse { } - (. $r.Logic @{ + $WebEvent = @{ 'Path' = '/'; 'Protocol' = 'http'; 'Endpoint' = ''; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false Assert-MockCalled Write-PodeFileResponse -Times 1 -Scope It } @@ -727,9 +772,11 @@ Describe 'Get-PodePublicMiddleware' { Mock Find-PodePublicRoute { return '/' } Mock Write-PodeFileResponse { } - (. $r.Logic @{ + $WebEvent = @{ 'Path' = '/'; 'Protocol' = 'http'; 'Endpoint' = ''; - }) | Should Be $false + } + + (. $r.Logic) | Should Be $false Assert-MockCalled Write-PodeFileResponse -Times 1 -Scope It } From beab6ea6d99de012fd29e0d9ceb296dc6075845d Mon Sep 17 00:00:00 2001 From: Matthew Kelly Date: Sun, 1 Nov 2020 16:15:25 +0000 Subject: [PATCH 2/4] #618: update docs for the WebEvent var --- docs/Hosting/IIS.md | 2 +- docs/Hosting/SmtpServer.md | 2 +- docs/Tutorials/Authentication/Inbuilt/UserFile.md | 2 +- .../Authentication/Methods/ClientCertificate.md | 2 +- docs/Tutorials/Authentication/Methods/Custom.md | 5 ++--- docs/Tutorials/Middleware/Overview.md | 10 +++++----- docs/Tutorials/Middleware/Types/BodyParsing.md | 2 +- docs/Tutorials/Middleware/Types/Sessions.md | 2 +- docs/Tutorials/Misc/UploadFiles.md | 2 +- docs/Tutorials/Routes/Examples/LoginPage.md | 6 +++--- docs/Tutorials/Routes/Overview.md | 10 +++++----- docs/Tutorials/WebEvent.md | 7 +++---- 12 files changed, 25 insertions(+), 27 deletions(-) diff --git a/docs/Hosting/IIS.md b/docs/Hosting/IIS.md index 76b9157c5..21761e4a3 100644 --- a/docs/Hosting/IIS.md +++ b/docs/Hosting/IIS.md @@ -110,7 +110,7 @@ Start-PodeServer { } ``` -If the required header is missing, then Pode responds with a 401. The retrieved user, like other authentication, is set in the web event's `Auth.User` and contains the same information as Pode's inbuilt Windows AD authenticator: +If the required header is missing, then Pode responds with a 401. The retrieved user, like other authentication, is set on the [web event](../../../WebEvent)'s `$WebEvent.Auth.User` property, and contains the same information as Pode's inbuilt Windows AD authenticator: | Name | Type | Description | | ---- | ---- | ----------- | diff --git a/docs/Hosting/SmtpServer.md b/docs/Hosting/SmtpServer.md index 3ad49c5d5..96916bfb2 100644 --- a/docs/Hosting/SmtpServer.md +++ b/docs/Hosting/SmtpServer.md @@ -18,7 +18,7 @@ Start-PodeServer { } ``` -The SMTP Handler will be passed the a `$SmtpEvent` object, that conatins te Request, Response, and Email: +The SMTP Handler will be passed the a `$SmtpEvent` object, that contains te Request, Response, and Email: | Name | Type | Description | | ---- | ---- | ----------- | diff --git a/docs/Tutorials/Authentication/Inbuilt/UserFile.md b/docs/Tutorials/Authentication/Inbuilt/UserFile.md index a08d6cd81..334aef0fb 100644 --- a/docs/Tutorials/Authentication/Inbuilt/UserFile.md +++ b/docs/Tutorials/Authentication/Inbuilt/UserFile.md @@ -61,7 +61,7 @@ Start-PodeServer { ### User Object -The User object returned, and accessible on Routes, and other functions via the web event's `$WebEvent.Auth.User`, will contain the following information: +The User object returned, and accessible on Routes, and other functions via the [web event](../../../WebEvent)'s `$WebEvent.Auth.User` property, will contain the following information: | Name | Type | Description | | ---- | ---- | ----------- | diff --git a/docs/Tutorials/Authentication/Methods/ClientCertificate.md b/docs/Tutorials/Authentication/Methods/ClientCertificate.md index ad6589931..e9615fc7c 100644 --- a/docs/Tutorials/Authentication/Methods/ClientCertificate.md +++ b/docs/Tutorials/Authentication/Methods/ClientCertificate.md @@ -2,7 +2,7 @@ Client Certificate Authentication is when the server requires the client to supply a certificate on the request, to verify themselves with the server. This only works over HTTPS connections. -If at any point to you need to access the client's certificate outside of this validator, then it can be found on the web event object at `Request.ClientCertificate`. +If at any point to you need to access the client's certificate outside of this validator, then it can be found on the [web event](../../../WebEvent) object at `Request.ClientCertificate`. ## Setup diff --git a/docs/Tutorials/Authentication/Methods/Custom.md b/docs/Tutorials/Authentication/Methods/Custom.md index e5a4e6e34..c76e4c36b 100644 --- a/docs/Tutorials/Authentication/Methods/Custom.md +++ b/docs/Tutorials/Authentication/Methods/Custom.md @@ -8,7 +8,7 @@ To setup and start using Custom authentication in Pode you use the `New-PodeAuth Let's say we wanted something similar to [`Form`](../Form) Authentication, but it requires a third piece of information: `ClientName`. To setup Custom Authentication for this method, you'll need to specify the parsing logic within the `-ScriptBlock` of the [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) function. -The `-ScriptBlock` on [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) will be passed the current [web event](../../../WebEvent) (containing the `Request`/`Response` objects, and other pieces of information much like on Routes or Middleware). In this script you can parse the Request payload/headers for any credential information that needs validating. Once sourced the data returned from the script should be an `array`, which will then splatted onto the `-ScriptBlock` from your [`Add-PodeAuth`](../../../../Functions/Authentication/Add-PodeAuth) function: +The `-ScriptBlock` on [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) will have access to the current [web event](../../../WebEvent) variable: `$WebEvent`. In this script you can parse the Request payload/headers for any credential information that needs validating. Once sourced the data returned from the script should be an `array`, which will then splatted onto the `-ScriptBlock` from your [`Add-PodeAuth`](../../../../Functions/Authentication/Add-PodeAuth) function: ```powershell Start-PodeServer { @@ -49,11 +49,10 @@ Start-PodeServer { The typical setup of authentication is that you create some scheme to parse the request ([`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme)), and then you pipe this into a validator to validate the parsed user's credentials ([`Add-PodeAuth`](../../../../Functions/Authentication/Add-PodeAuth)). -There is however also an optional `-PostValidator` ScriptBlock that can be passed to your Custom Authentication scheme on the [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) function. This `-PostValidator` script runs after normal user validation, and is supplied the current [web event](../../../WebEvent), the original splatted array returned from the [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) ScriptBlock, the result HashTable from the user validator from `Add-PodeAuth`, and the `-ArgumentList` HashTable from `New-PodeAuthScheme`. You can use this script to re-generate any hashes for further validation, but if successful you *must* return the User object again (ie: re-return the last parameter which is the original validation result). +There is however also an optional `-PostValidator` ScriptBlock that can be passed to your Custom Authentication scheme on the [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) function. This `-PostValidator` script runs after normal user validation, and also has access to the current [web event](../../../WebEvent). The original splatted array returned from the [`New-PodeAuthScheme`](../../../../Functions/Authentication/New-PodeAuthScheme) ScriptBlock, the result HashTable from the user validator from `Add-PodeAuth`, and the `-ArgumentList` HashTable from `New-PodeAuthScheme` are supplied as parameters. You can use this script to re-generate any hashes for further validation, but if successful you *must* return the User object again (ie: re-return the last parameter which is the original validation result). For example, if you have a post validator script for the above Client Custom Authentication, then it would be supplied the following parameters: -* Web Event * ClientName * Username * Password diff --git a/docs/Tutorials/Middleware/Overview.md b/docs/Tutorials/Middleware/Overview.md index 2834c0b14..5ba070675 100644 --- a/docs/Tutorials/Middleware/Overview.md +++ b/docs/Tutorials/Middleware/Overview.md @@ -2,15 +2,15 @@ Middleware in Pode allows you to observe and edit the request/response objects for a current [web event](../../WebEvent) - you can alter the response, add custom objects to the [web event](../../WebEvent) for later use, or terminate the response without processing the main Route logic. -Middleware is supported in both a global scope, using [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware), as well as at the Route level using the `-Middleware` parameter on [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware), +Middleware is supported in both a global scope, using [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware), as well as at the Route level using the `-Middleware` parameter on [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware). -Pode itself has some inbuilt Middleware, which is overridable, so you can use your own custom middleware. For example, Pode has inbuilt Middleware for rate limiting, but you can override this with [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware) and the Name `__pode_mw_rate_limit__` (more on the [Access Rules](../Types/AccessRules) and [Rate Limiting](../Types/RateLimiting) page). +Pode itself has some inbuilt Middleware, which is overridable, so you can use your own custom middleware. For example, Pode has inbuilt Middleware for rate limiting, but you can override this with [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware) and the Name `__pode_mw_rate_limit__` (more on the [Access Rules](../Types/AccessRules) and [Rate Limiting](../Types/RateLimiting) page). ## Global Middleware -To setup and use middleware in Pode you use the Middleware function: [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware). This will setup global middleware that will run, in the order created, on every request prior to any Route logic being invoked. +To setup and use middleware in Pode you use the Middleware function: [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware). This will setup global middleware that will run, in the order created, on every request prior to any Route logic being invoked. -The function takes a ScriptBlock, which itself accepts a single parameter for the current [web event](../../WebEvent) (similar to Routes). The event object passed contains the current `Request` and `Response` objects - you can also add more custom objects to it, as the event is just a `hashtable`. +The function takes a ScriptBlock, which has access to the current [web event](../../WebEvent) variable: `$WebEvent`. The event object contains the current `Request` and `Response` objects - you can also add more custom objects to it, as the event is just a `hashtable`. If you want to keep processing and proceed to the next Middleware/Route then `return $true` from the ScriptBlock, otherwise `return $false` and the response will be closed immediately. @@ -50,7 +50,7 @@ Start-PodeServer { ## Route Middleware -Custom middleware on a Route is basically the same as above however, you don't use the main Middleware functions and instead insert it straight on the Route. To do this, you can use the `-Middleware` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function. +Custom middleware on a Route is basically the same as above however, you don't use the main Middleware functions and instead insert it straight on the Route. To do this, you can use the `-Middleware` parameter on the [`Add-PodeRoute`](../../../Functions/Routes/Add-PodeRoute) function. The middleware on a route can either be a single `scriptblock` or an an array of `scriptblocks`. Middleware defined on routes will be run before the route itself, but after any global middleware that may have been configured. diff --git a/docs/Tutorials/Middleware/Types/BodyParsing.md b/docs/Tutorials/Middleware/Types/BodyParsing.md index 318b47218..3dd53fd4d 100644 --- a/docs/Tutorials/Middleware/Types/BodyParsing.md +++ b/docs/Tutorials/Middleware/Types/BodyParsing.md @@ -25,7 +25,7 @@ Add-PodeBodyParser -ContentType 'application/json' -ScriptBlock { } ``` -This can then be accessed the normal way within a Route from the `.Data` object on the supplied event: +This can then be accessed the normal way within a Route from the `.Data` property on the accessible `$WebEvent`: ```powershell Add-PodeRoute -Method Post -Path '/' -ScriptBlock { diff --git a/docs/Tutorials/Middleware/Types/Sessions.md b/docs/Tutorials/Middleware/Types/Sessions.md index c0cc4036b..37f7363d4 100644 --- a/docs/Tutorials/Middleware/Types/Sessions.md +++ b/docs/Tutorials/Middleware/Types/Sessions.md @@ -86,7 +86,7 @@ $store | Add-Member -MemberType NoteProperty -Name Delete -Value { ## Session Data -To add data to a session you can utilise the `.Session.Data` object within the [web event](../../../WebEvent) object supplied to a Route - or other Middleware. The data will be saved at the end of the route automatically using Endware. When a request is made using the same sessionId, the data is loaded from the store. +To add data to a session you can utilise the `.Session.Data` property within the [web event](../../../WebEvent) object accessible in a Route - or other Middleware. The data will be saved at the end of the route automatically using Endware. When a request is made using the same sessionId, the data is loaded from the store. ### Example diff --git a/docs/Tutorials/Misc/UploadFiles.md b/docs/Tutorials/Misc/UploadFiles.md index b00763d7b..878dfde6c 100644 --- a/docs/Tutorials/Misc/UploadFiles.md +++ b/docs/Tutorials/Misc/UploadFiles.md @@ -1,6 +1,6 @@ # Uploading Files -Pode's inbuilt middleware supports parsing a request's body/payload and query string, and this also extends to uploading files via a ``. Like how POST data can be accessed in a Route via the passed [web event](../../WebEvent) as `$WebEvent.Data[]`, uploaded files can be accessed via `$WebEvent.Files[]`. +Pode's inbuilt middleware supports parsing a request's body/payload and query string, and this also extends to uploading files via a ``. Like how POST data can be accessed in a Route via the [web event](../../WebEvent) as `$WebEvent.Data[]`, uploaded files can be accessed via `$WebEvent.Files[]`. !!! important In order for uploaded files to work, your `` must contain `enctype="multipart/form-data"` diff --git a/docs/Tutorials/Routes/Examples/LoginPage.md b/docs/Tutorials/Routes/Examples/LoginPage.md index a1bf6138b..54caa71a0 100644 --- a/docs/Tutorials/Routes/Examples/LoginPage.md +++ b/docs/Tutorials/Routes/Examples/LoginPage.md @@ -20,7 +20,7 @@ server.ps1 ## Server -To start off this script, you'll need to have the main [`Start-PodeServer`](../../../../Functions/Core/Start-PodeServer) function; here we'll use 2 threads to handle requests: +To start off this script, you'll need to have the main [`Start-PodeServer`](../../../../Functions/Core/Start-PodeServer) function; here we'll use 2 threads to handle requests: ```powershell Start-PodeServer -Thread 2 { @@ -28,14 +28,14 @@ Start-PodeServer -Thread 2 { } ``` -Next, we'll need to use the [`Add-PodeEndpoint`](../../../../Functions/Core/Add-PodeEndpoint) function to listen on an endpoint and then specify the View Engine as using `.pode` files: +Next, we'll need to use the [`Add-PodeEndpoint`](../../../../Functions/Core/Add-PodeEndpoint) function to listen on an endpoint and then specify the View Engine as using `.pode` files: ```powershell Add-PodeEndpoint -Address * -Port 8080 -Protocol Http Set-PodeViewEngine -Type Pode ``` -To use sessions for our authentication (so we can stay logged in), we need to setup Session Middleware using the [`Enable-PodeSessionMiddleware`](../../../../Functions/Middleware/Enable-PodeSessionMiddleware) function. Here our sessions will last for 2 minutes, and will be extended on each request: +To use sessions for our authentication (so we can stay logged in), we need to setup Session Middleware using the [`Enable-PodeSessionMiddleware`](../../../../Functions/Middleware/Enable-PodeSessionMiddleware) function. Here our sessions will last for 2 minutes, and will be extended on each request: ```powershell Enable-PodeSessionMiddleware -Secret 'schwifty' -Duration 120 -Extend diff --git a/docs/Tutorials/Routes/Overview.md b/docs/Tutorials/Routes/Overview.md index c74e0cb7e..a760f93e7 100644 --- a/docs/Tutorials/Routes/Overview.md +++ b/docs/Tutorials/Routes/Overview.md @@ -32,11 +32,11 @@ Here, anyone who calls `http://localhost:8080/ping` will receive the following r } ``` -The scriptblock for the route will be supplied with a single argument that contains information about the current [web event](../../WebEvent). This argument will contain the `Request` and `Response` objects, `Data` (from POST), and the `Query` (from the query string of the URL), as well as any `Parameters` from the route itself (eg: `/:accountId`). +The scriptblock for the route will have access to the `$WebEvent` variable which contains information about the current [web event](../../WebEvent). This argument will contain the `Request` and `Response` objects, `Data` (from POST), and the `Query` (from the query string of the URL), as well as any `Parameters` from the route itself (eg: `/:accountId`). ## Payloads -The following is an example of using data from a request's payload - ie, the data in the body of POST request. To retrieve values from the payload you can use the `.Data` hashtable on the supplied web-session to a route's logic. This example will get the `userId` and "find" user, returning the users data: +The following is an example of using data from a request's payload - ie, the data in the body of POST request. To retrieve values from the payload you can use the `.Data` property on the `$WebEvent` variable to a route's logic. This example will get the `userId` and "find" user, returning the users data: ```powershell Start-PodeServer { @@ -69,7 +69,7 @@ Invoke-WebRequest -Uri 'http://localhost:8080/users' -Method Post -Body '{ "user ## Query Strings -The following is an example of using data from a request's query string. To retrieve values from the query string you can use the `.Query` hashtable on the supplied web-session to a route's logic. This example will return a user based on the `userId` supplied: +The following is an example of using data from a request's query string. To retrieve values from the query string you can use the `.Query` property from the `$WebEvent` variable. This example will return a user based on the `userId` supplied: ```powershell Start-PodeServer { @@ -96,7 +96,7 @@ Invoke-WebRequest -Uri 'http://localhost:8080/users?userId=12345' -Method Get ## Parameters -The following is an example of using values supplied on a request's URL using parameters. To retrieve values that match a request's URL parameters you can use the `.Parameters` hashtable on the supplied web-session to a route's logic. This example will get the `:userId` and "find" user, returning the users data: +The following is an example of using values supplied on a request's URL using parameters. To retrieve values that match a request's URL parameters you can use the `.Parameters` property from the `$WebEvent` variable. This example will get the `:userId` and "find" user, returning the users data: ```powershell Start-PodeServer { @@ -169,7 +169,7 @@ The following is the structure of the Route object internally, as well as the ob | Name | Type | Description | | ---- | ---- | ----------- | -| Arguments | object[] | Array of arguments that are splatted onto the route's scriptblock (after the web event) | +| Arguments | object[] | Array of arguments that are splatted onto the route's scriptblock | | ContentType | string | The content type to use when parsing the payload in the request | | Endpoint | hashtable | Contains the Address, Protocol, and Name of the Endpoint the route is bound to | | ErrorType | string | Content type of the error page to use for the route | diff --git a/docs/Tutorials/WebEvent.md b/docs/Tutorials/WebEvent.md index f3813eaa3..e45605565 100644 --- a/docs/Tutorials/WebEvent.md +++ b/docs/Tutorials/WebEvent.md @@ -1,13 +1,12 @@ # Web Event -When a request is made to your server, a "web event" object is created that contains a lot of useful information about the request (and the response!). +When a request is made to your server, a "web event" object is created. This object contains a lot of useful information about the request, and the response. -This web event is a normal HashTable, and is always supplied as the first parameter to your Routes, Middleware, Endware, custom Authentication type ScriptBlocks: +This web event is a normal HashTable, and is always accessible from your Routes, Middleware, Endware, and Authentication ScriptBlocks as the `$WebEvent` variable: ```powershell Add-PodeRoute -Method Get -Path '/' -ScriptBlock { - param($e) - # that $e is the web event! + $WebEvent | Out-Default } ``` From ce7ac216b10390c6d0ff2b8e14830d715b2c4bda Mon Sep 17 00:00:00 2001 From: Matthew Kelly Date: Sun, 1 Nov 2020 16:47:39 +0000 Subject: [PATCH 3/4] #618: update migrate docs --- docs/Getting-Started/Migrating/1X-to-2X.md | 37 +++++++++++++++---- docs/Tutorials/Authentication/Methods/Form.md | 2 +- docs/Tutorials/Configuration.md | 2 +- docs/Tutorials/Logging/Methods/Custom.md | 2 +- docs/Tutorials/Logging/Types/Custom.md | 8 ++-- docs/Tutorials/Logging/Types/Errors.md | 2 +- docs/Tutorials/Logging/Types/Requests.md | 4 +- docs/Tutorials/Middleware/Overview.md | 2 +- .../Tutorials/Middleware/Types/AccessRules.md | 2 +- .../Middleware/Types/RateLimiting.md | 2 +- docs/Tutorials/Routes/Examples/WebPages.md | 4 +- .../Routes/Utilities/ContentTypes.md | 2 +- docs/Tutorials/Routes/Utilities/ErrorPages.md | 8 ++-- .../Routes/Utilities/FlashMessages.md | 4 +- .../Tutorials/Routes/Utilities/Redirecting.md | 2 +- docs/Tutorials/SharedState.md | 2 +- docs/Tutorials/Views/ThirdParty.md | 4 +- 17 files changed, 56 insertions(+), 33 deletions(-) diff --git a/docs/Getting-Started/Migrating/1X-to-2X.md b/docs/Getting-Started/Migrating/1X-to-2X.md index 5edd78b05..230991d5c 100644 --- a/docs/Getting-Started/Migrating/1X-to-2X.md +++ b/docs/Getting-Started/Migrating/1X-to-2X.md @@ -8,7 +8,30 @@ In Pode v2.X the Server got the biggest overhaul with the dropping of HttpListen If you were previously specifying `-Type Pode` on your [`Start-PodeServer`](../../../Functions/Core/Start-PodeServer), then you no longer need to - all servers now default to using Pode new .NET Core socket listener. -### Endpoints +## Web Event + +Originally the Web Event object was the first parameter supplied to the ScriptBlocks of Routes, Middleware, and Endware. These already all had access to the main `$WebEvent` object, including Authentication, without the need to supply it as a parameter. + +In 2.0, this first event parameter has been dropped, and you should now use the main `$WebEvent` object. + +So from the following: +```powershell +Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + param($e) + Write-PodeJsonResponse -Value @{ Result = $e.Data['value']} +} +``` + +To this: +```powershell +Add-PodeRoute -Method Get -Path '/' -ScriptBlock { + Write-PodeJsonResponse -Value @{ Result = $WebEvent.Data['value']} +} +``` + +This also applies to Middleware, Endware, and Authentication. + +## Endpoints With the dropping of HttpListener, the `-Certificate` parameter is now the old `-CertificateFile` parameter. The `-RawCertificate` parameter has been renamed, and it now called `-X509Certificate`. @@ -45,7 +68,7 @@ to: } ``` -### Authentication +## Authentication Authentication underwent a hefty change in 2.0, with `Get-PodeAuthMiddleware` being removed. @@ -63,7 +86,7 @@ Furthermore, the OpenAPI functions for `Set-PodeOAAuth` and `Set-PodeOAGlobalAut On `Add-PodeAuth`, `Add-PodeAuthWindowsAd`, and `Add-PodeAuthUserFile` the `-Type` parameter has been renamed to `-Scheme`. If you have always piped `New-PodeAuthScheme` (formally `New-PodeAuthType`) into them, then this won't affect you. -### Endpoint and Protocol +## Endpoint and Protocol On the following functions: @@ -82,7 +105,7 @@ Further to this, if no `-Name` is supplied to [`Add-PodeEndpoint`](../../../Func The 2.0 release sees a big change to some scoping issues in Pode, around modules/snapins/functions and variables. For more information, see the new page on [Scoping](../../../Tutorials/Scoping). -#### Modules/Snapins +## Modules/Snapins You can now use `Import-Module`, or `Add-PSSnapin`, and Pode will automatically import all loaded modules/snapins into its runspaces: @@ -121,7 +144,7 @@ To disable the auto-import, you can do so via the `server.psd1` configuration fi } ``` -#### Functions +### Functions Local functions are now automatically imported into Pode's runspaces! This makes it a little simpler to use quick functions in Pode: @@ -166,7 +189,7 @@ To disable the auto-import, you can do so via the `server.psd1` configuration fi } ``` -#### Variables +### Variables You can now define local variables, and use the `$using:` syntax in almost all `-ScriptBlock` parameters, like: @@ -195,7 +218,7 @@ Start-PodeServer -ScriptBlock { } ``` -### Test Functions +## Test Functions If you're using any of the following: diff --git a/docs/Tutorials/Authentication/Methods/Form.md b/docs/Tutorials/Authentication/Methods/Form.md index 26b579771..58379ce4a 100644 --- a/docs/Tutorials/Authentication/Methods/Form.md +++ b/docs/Tutorials/Authentication/Methods/Form.md @@ -4,7 +4,7 @@ Form Authentication is for when you're using a `` in HTML, and you submit ## Setup -To setup and start using Form Authentication in Pode you use the `New-PodeAuthScheme -Form` function, and then pipe this into the [`Add-PodeAuth`](../../../../Functions/Authentication/Add-PodeAuth) function: +To setup and start using Form Authentication in Pode you use the `New-PodeAuthScheme -Form` function, and then pipe this into the [`Add-PodeAuth`](../../../../Functions/Authentication/Add-PodeAuth) function: ```powershell Start-PodeServer { diff --git a/docs/Tutorials/Configuration.md b/docs/Tutorials/Configuration.md index e62d6b367..a2fab6bb7 100644 --- a/docs/Tutorials/Configuration.md +++ b/docs/Tutorials/Configuration.md @@ -27,7 +27,7 @@ After this, you can put whatever else you want into the configuration file. The configuration file is automatically loaded when you start your server. Pode will look in the root directory of your server for a `server.psd1` file, and if found it will be loaded internally. -Within your scripts you can use the [`Get-PodeConfig`](../../Functions/Utilities/Get-PodeConfig) function, which will return the values of the relevant configuration file. +Within your scripts you can use the [`Get-PodeConfig`](../../Functions/Utilities/Get-PodeConfig) function, which will return the values of the relevant configuration file. For example, say you have the following `server.psd1`: diff --git a/docs/Tutorials/Logging/Methods/Custom.md b/docs/Tutorials/Logging/Methods/Custom.md index b0a9b0078..8fe03a7b1 100644 --- a/docs/Tutorials/Logging/Methods/Custom.md +++ b/docs/Tutorials/Logging/Methods/Custom.md @@ -7,7 +7,7 @@ These custom method can be used for any log type - Requests, Error, or Custom. The ScriptBlock you create will be supplied two arguments: 1. The item to be logged. This could be a string (from Requests/Errors), or any custom type. -2. The options you supplied on [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). +2. The options you supplied on [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). ## Examples diff --git a/docs/Tutorials/Logging/Types/Custom.md b/docs/Tutorials/Logging/Types/Custom.md index f4ee2669b..4b1eda382 100644 --- a/docs/Tutorials/Logging/Types/Custom.md +++ b/docs/Tutorials/Logging/Types/Custom.md @@ -1,13 +1,13 @@ # Custom -You can define Custom logging types in Pode by using the [`Add-PodeLogger`](../../../../Functions/Logging/Add-PodeLogger) function. Much like Requests and Errors, this function too accepts any logging method from [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). +You can define Custom logging types in Pode by using the [`Add-PodeLogger`](../../../../Functions/Logging/Add-PodeLogger) function. Much like Requests and Errors, this function too accepts any logging method from [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). -When adding a Custom logger, you supply a `-ScriptBlock` plus an array of optional arguments in `-ArgumentList`. The function also requires a unique `-Name`, so that it can be referenced from the [`Write-PodeLog`](../../../../Functions/Logging/Write-PodeLog) function. +When adding a Custom logger, you supply a `-ScriptBlock` plus an array of optional arguments in `-ArgumentList`. The function also requires a unique `-Name`, so that it can be referenced from the [`Write-PodeLog`](../../../../Functions/Logging/Write-PodeLog) function. The ScriptBlock will be supplied with the following arguments: -1. The item to log that was supplied via [`Write-PodeLog`](../../../../Functions/Logging/Write-PodeLog). -2. The arguments that were supplied from [`Add-PodeLogger`](../../../../Functions/Logging/Add-PodeLogger)'s `-ArgumentList` parameter. +1. The item to log that was supplied via [`Write-PodeLog`](../../../../Functions/Logging/Write-PodeLog). +2. The arguments that were supplied from [`Add-PodeLogger`](../../../../Functions/Logging/Add-PodeLogger)'s `-ArgumentList` parameter. ## Examples diff --git a/docs/Tutorials/Logging/Types/Errors.md b/docs/Tutorials/Logging/Types/Errors.md index b661ca896..d5e36a5e4 100644 --- a/docs/Tutorials/Logging/Types/Errors.md +++ b/docs/Tutorials/Logging/Types/Errors.md @@ -6,7 +6,7 @@ It also has support for error levels (such as Error, Warning, Verbose), with sup ## Enabling -To enable and use the Error logging you use the [`Enable-PodeErrorLogging`](../../../../Functions/Logging/Enable-PodeErrorLogging) function, supplying a logging method from [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). You can supply your own errors to be logged by using [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). +To enable and use the Error logging you use the [`Enable-PodeErrorLogging`](../../../../Functions/Logging/Enable-PodeErrorLogging) function, supplying a logging method from [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). You can supply your own errors to be logged by using [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). When Pode logs an error, the information being logged is as follows: diff --git a/docs/Tutorials/Logging/Types/Requests.md b/docs/Tutorials/Logging/Types/Requests.md index 43b0305bd..627123c4c 100644 --- a/docs/Tutorials/Logging/Types/Requests.md +++ b/docs/Tutorials/Logging/Types/Requests.md @@ -4,9 +4,9 @@ Pode has inbuilt Request logging logic, that will parse and return a valid log i ## Enabling -To enable and use the Request logging you use the [`Enable-PodeRequestLogging`](../../../../Functions/Logging/Enable-PodeRequestLogging) function, supplying a logging method from [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). +To enable and use the Request logging you use the [`Enable-PodeRequestLogging`](../../../../Functions/Logging/Enable-PodeRequestLogging) function, supplying a logging method from [`New-PodeLoggingMethod`](../../../../Functions/Logging/New-PodeLoggingMethod). -The Request type logic will format a string using [Combined Log Format](https://httpd.apache.org/docs/1.3/logs.html#combined). This string is then supplied to the logging method's scriptblock. If you're using a Custom logging method and want the raw hashtable instead, you can supply `-Raw` to [`Enable-PodeRequestLogging`](../../../../Functions/Logging/Enable-PodeRequestLogging). +The Request type logic will format a string using [Combined Log Format](https://httpd.apache.org/docs/1.3/logs.html#combined). This string is then supplied to the logging method's scriptblock. If you're using a Custom logging method and want the raw hashtable instead, you can supply `-Raw` to [`Enable-PodeRequestLogging`](../../../../Functions/Logging/Enable-PodeRequestLogging). ## Examples diff --git a/docs/Tutorials/Middleware/Overview.md b/docs/Tutorials/Middleware/Overview.md index 5ba070675..5a57ff733 100644 --- a/docs/Tutorials/Middleware/Overview.md +++ b/docs/Tutorials/Middleware/Overview.md @@ -100,7 +100,7 @@ Although you can define your own custom middleware, Pode does have some inbuilt ## Overriding Inbuilt -Pode has inbuilt Middleware as defined in the order of running above. Sometimes you probably don't want to use the inbuilt rate limiting, and use a custom rate limiting library that utilises REDIS instead. Each of the inbuilt Middleware have a defined name, that you can pass to the [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware) function via the `-Name` parameter: +Pode has inbuilt Middleware as defined in the order of running above. Sometimes you probably don't want to use the inbuilt rate limiting, and use a custom rate limiting library that utilises REDIS instead. Each of the inbuilt Middleware have a defined name, that you can pass to the [`Add-PodeMiddleware`](../../../Functions/Core/Add-PodeMiddleware) function via the `-Name` parameter: * Access Control - `__pode_mw_access__` * Rate Limiting - `__pode_mw_rate_limit__` diff --git a/docs/Tutorials/Middleware/Types/AccessRules.md b/docs/Tutorials/Middleware/Types/AccessRules.md index 2176c7166..fc6a50c35 100644 --- a/docs/Tutorials/Middleware/Types/AccessRules.md +++ b/docs/Tutorials/Middleware/Types/AccessRules.md @@ -39,7 +39,7 @@ Add-PodeAccessRule -Access Deny -Type IP -Values 'all' Since access rules are an inbuilt Middleware in Pode, then when you setup rules the point at which the rules are checked on the request lifecycle is fixed (see [here](../../Overview/#order-of-running)). -This means you can override the inbuilt access rule logic with your own custom logic, using the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. To override the access rule logic you can pass `__pode_mw_access__` to the `-Name` parameter of the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. +This means you can override the inbuilt access rule logic with your own custom logic, using the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. To override the access rule logic you can pass `__pode_mw_access__` to the `-Name` parameter of the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. The following example uses access rules, and defines Middleware that will override the inbuilt access logic: diff --git a/docs/Tutorials/Middleware/Types/RateLimiting.md b/docs/Tutorials/Middleware/Types/RateLimiting.md index 35e03c3c5..9bcf5bf74 100644 --- a/docs/Tutorials/Middleware/Types/RateLimiting.md +++ b/docs/Tutorials/Middleware/Types/RateLimiting.md @@ -68,7 +68,7 @@ Add-PodeLimitRule -Type Endpoint -Values 'User' -Limit 5 -Seconds 1 Since rate limiting is an inbuilt Middleware, then when you setup rules via the [`Add-PodeLimitRule`](../../../../Functions/Middleware/Add-PodeLimitRule) function the point at which the limit is checked on the request lifecycle is fixed (see [here](../../Overview/#order-of-running)). -This means you can override the inbuilt rate limiting logic, with your own custom logic, using the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. To override the rate limiting logic you can pass `__pode_mw_rate_limit__` to the `-Name` parameter of the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. +This means you can override the inbuilt rate limiting logic, with your own custom logic, using the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. To override the rate limiting logic you can pass `__pode_mw_rate_limit__` to the `-Name` parameter of the [`Add-PodeMiddleware`](../../../../Functions/Core/Add-PodeMiddleware) function. The following example uses rate limiting, and defines Middleware that will override the inbuilt limiting logic: diff --git a/docs/Tutorials/Routes/Examples/WebPages.md b/docs/Tutorials/Routes/Examples/WebPages.md index 47caa997c..851a80344 100644 --- a/docs/Tutorials/Routes/Examples/WebPages.md +++ b/docs/Tutorials/Routes/Examples/WebPages.md @@ -4,9 +4,9 @@ Serving up web pages via Pode is simple, you can either write your pages in HTML ## Basics -To serve up a web page you use the [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function, and if you're using a dynamic template (like [`.pode`](../../../Views/Pode) files) to render your views use the [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function. +To serve up a web page you use the [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function, and if you're using a dynamic template (like [`.pode`](../../../Views/Pode) files) to render your views use the [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function. -When you use the [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function to serve a web page, the path to the view must be relative to the `/views` directory. For example, the following will display the `/views/index.html` page: +When you use the [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function to serve a web page, the path to the view must be relative to the `/views` directory. For example, the following will display the `/views/index.html` page: ```powershell Start-PodeServer { diff --git a/docs/Tutorials/Routes/Utilities/ContentTypes.md b/docs/Tutorials/Routes/Utilities/ContentTypes.md index 28ae99da9..41800c84a 100644 --- a/docs/Tutorials/Routes/Utilities/ContentTypes.md +++ b/docs/Tutorials/Routes/Utilities/ContentTypes.md @@ -1,6 +1,6 @@ # Content Types -Any payload supplied in a web request is normally parsed using the content type on the request's headers. However, it's possible to override - or *force* - a specific content type on routes when parsing the payload. This can be achieved by either using the `-ContentType` parameter on the [`Add-PodeRoute`](../../../../Functions/Routes/Add-PodeRoute) function, or using the [`server.psd1`](../../Configuration) configuration file. +Any payload supplied in a web request is normally parsed using the content type on the request's headers. However, it's possible to override - or *force* - a specific content type on routes when parsing the payload. This can be achieved by either using the `-ContentType` parameter on the [`Add-PodeRoute`](../../../../Functions/Routes/Add-PodeRoute) function, or using the [`server.psd1`](../../Configuration) configuration file. When a specific content type is supplied then any payload will be parsed as that content type only - even if the content type is supplied on the web request's header. This way, you can force a route to only accept a certain content type. diff --git a/docs/Tutorials/Routes/Utilities/ErrorPages.md b/docs/Tutorials/Routes/Utilities/ErrorPages.md index 50e865e28..ff2d05938 100644 --- a/docs/Tutorials/Routes/Utilities/ErrorPages.md +++ b/docs/Tutorials/Routes/Utilities/ErrorPages.md @@ -9,7 +9,7 @@ During web requests, Pode has some default status codes that can be returned thr * `429` if the rate limit is reached * `500` for a complete failure -Status codes that are 400+ will be rendered as an error page, unless the `-NoErrorPage` switch is passed to the [`Set-PodeResponseStatus`](../../../../Functions/Responses/Set-PodeResponseStatus) function. Pode itself has inbuilt error pages (HTML, JSON, and XML), but you can override these pages using custom error pages ([described below](#error-pages)). +Status codes that are 400+ will be rendered as an error page, unless the `-NoErrorPage` switch is passed to the [`Set-PodeResponseStatus`](../../../../Functions/Responses/Set-PodeResponseStatus) function. Pode itself has inbuilt error pages (HTML, JSON, and XML), but you can override these pages using custom error pages ([described below](#error-pages)). If the error page being generated is dynamic, then the following `$data` is supplied and can be used the same as in views: @@ -18,11 +18,11 @@ If the error page being generated is dynamic, then the following `$data` is supp * The URL that threw the error * The content-type of the error page being generated -They're also supplied details of any exception passed to the [`Set-PodeResponseStatus`](../../../../Functions/Responses/Set-PodeResponseStatus) function, which can be rendered [if enabled](#exceptions) via the `server.psd1` configuration file. +They're also supplied details of any exception passed to the [`Set-PodeResponseStatus`](../../../../Functions/Responses/Set-PodeResponseStatus) function, which can be rendered [if enabled](#exceptions) via the `server.psd1` configuration file. ## Status Codes -The [`Set-PodeResponseStatus`](../../../../Functions/Responses/Set-PodeResponseStatus) function allows you to set your own status code on the response, as well as a custom description. If the status code was triggered by an exception being thrown, then you can also supply this so it can be rendered on any [error pages](#error-pages). +The [`Set-PodeResponseStatus`](../../../../Functions/Responses/Set-PodeResponseStatus) function allows you to set your own status code on the response, as well as a custom description. If the status code was triggered by an exception being thrown, then you can also supply this so it can be rendered on any [error pages](#error-pages). The following example will set the status code of the response to be `418`: @@ -90,7 +90,7 @@ An example file structure for `/errors` is as follows: By default Pode will always generate error pages as HTML, unless you enable strict content typing or routes patterns ([detailed later](#content-types)). !!! important - To use error pages with a view engine (such as `.pode`), you need to use the [`Set-PodeViewEngine`](../../../../Functions/Responses/Set-PodeViewEngine) function in your server. + To use error pages with a view engine (such as `.pode`), you need to use the [`Set-PodeViewEngine`](../../../../Functions/Responses/Set-PodeViewEngine) function in your server. #### Dynamic Data diff --git a/docs/Tutorials/Routes/Utilities/FlashMessages.md b/docs/Tutorials/Routes/Utilities/FlashMessages.md index 76445ed07..ebc2e184c 100644 --- a/docs/Tutorials/Routes/Utilities/FlashMessages.md +++ b/docs/Tutorials/Routes/Utilities/FlashMessages.md @@ -11,7 +11,7 @@ For example, in sign-up logic you could set a flash error message for an invalid The flash functions allow you to add, get, and remove messages on a user's session. -If you call [`Add-PodeFlashMessage`](../../../../Functions/Flash/Add-PodeFlashMessage) using the same Name multiple times, then the messages will be appended as an array. Calling [`Add-PodeFlashMessage`](../../../../Functions/Flash/Add-PodeFlashMessage) for a Name will remove all messages from the current session for the Name supplied. +If you call [`Add-PodeFlashMessage`](../../../../Functions/Flash/Add-PodeFlashMessage) using the same Name multiple times, then the messages will be appended as an array. Calling [`Add-PodeFlashMessage`](../../../../Functions/Flash/Add-PodeFlashMessage) for a Name will remove all messages from the current session for the Name supplied. The following is an example of adding a flash message to a session, this will add a message under the `email-error` key: @@ -33,7 +33,7 @@ Add-PodeRoute -Method Get -Path '/signup' -ScriptBlock { ## Views -The [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function has a helper switch (`-FlashMessages`) to load all current flash messages in the session, into the views data - to save time writing lots of [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) calls. When used, all messages will be loaded into the `$data` argument supplied to dynamic views, and accessible under `$data.flash`. +The [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) function has a helper switch (`-FlashMessages`) to load all current flash messages in the session, into the views data - to save time writing lots of [`Write-PodeViewResponse`](../../../../Functions/Responses/Write-PodeViewResponse) calls. When used, all messages will be loaded into the `$data` argument supplied to dynamic views, and accessible under `$data.flash`. For example, somewhere we could have a sign-up flow which fails validation and adds two messages to the session: diff --git a/docs/Tutorials/Routes/Utilities/Redirecting.md b/docs/Tutorials/Routes/Utilities/Redirecting.md index 430c04153..a27ceed37 100644 --- a/docs/Tutorials/Routes/Utilities/Redirecting.md +++ b/docs/Tutorials/Routes/Utilities/Redirecting.md @@ -4,7 +4,7 @@ Sometimes you just want a Route to redirect the user else where, be it to anothe ## Usage -When in a Route, to inform the client to redirect to a different endpoint you can use the [`Move-PodeResponseUrl`](../../../../Functions/Responses/Move-PodeResponseUrl) function. +When in a Route, to inform the client to redirect to a different endpoint you can use the [`Move-PodeResponseUrl`](../../../../Functions/Responses/Move-PodeResponseUrl) function. Supplying `-Url` will redirect the user to that URL, or you can supply a relative path o the server for the user to be redirected to. The `-Port` and `-Protocol` can be used separately or together, but not with `-Url`. Using `-Port`/`-Protocol` will use the URI of the current web request to generate the redirect URL. diff --git a/docs/Tutorials/SharedState.md b/docs/Tutorials/SharedState.md index f119b7a18..de05e71bf 100644 --- a/docs/Tutorials/SharedState.md +++ b/docs/Tutorials/SharedState.md @@ -7,7 +7,7 @@ You also have the option of saving the current state to a file, and then restori You can also use the State in combination with the [`Lock-PodeObject`](../../Functions/Utilities/Lock-PodeObject) function to ensure thread safety - if needed. !!! tip - It's wise to use the State in conjunction with the [`Lock-PodeObject`](../../Functions/Utilities/Lock-PodeObject) function, to ensure thread safety between runspaces. The event argument supplied to Routes, Handlers, Timers, Schedules, Middleware, Endware and Loggers each contain a `.Lockable` resource that can be supplied to the [`Lock-PodeObject`](../../Functions/Utilities/Lock-PodeObject) function. + It's wise to use the State in conjunction with the [`Lock-PodeObject`](../../Functions/Utilities/Lock-PodeObject) function, to ensure thread safety between runspaces. The event objects available to Routes, Handlers, Timers, Schedules, Middleware, Endware and Loggers each contain a `.Lockable` resource that can be supplied to the [`Lock-PodeObject`](../../Functions/Utilities/Lock-PodeObject) function. !!! warning If you omit the use of [`Lock-PodeObject`](../../Functions/Utilities/Lock-PodeObject), you will run into errors due to multi-threading. Only omit if you are *absolutely confident* you do not need locking. (ie: you set in state once and then only ever retrieve, never updating the variable). diff --git a/docs/Tutorials/Views/ThirdParty.md b/docs/Tutorials/Views/ThirdParty.md index 06eead4f5..90d378226 100644 --- a/docs/Tutorials/Views/ThirdParty.md +++ b/docs/Tutorials/Views/ThirdParty.md @@ -1,11 +1,11 @@ # Third Party Engines -Pode supports the use of third-party view engines, for example you could use the [EPS](https://github.com/straightdave/eps) or [PSHTML](https://github.com/Stephanevg/PSHTML) template engines. To do this you'll need to supply a `scriptblock` to the [`Set-PodeViewEngine`](../../../Functions/Responses/Set-PodeViewEngine) function which tells Pode how use the third-party engine to render views. +Pode supports the use of third-party view engines, for example you could use the [EPS](https://github.com/straightdave/eps) or [PSHTML](https://github.com/Stephanevg/PSHTML) template engines. To do this you'll need to supply a `scriptblock` to the [`Set-PodeViewEngine`](../../../Functions/Responses/Set-PodeViewEngine) function which tells Pode how use the third-party engine to render views. This custom `scriptblock` will be supplied with two arguments: 1. `$path`: The path to the file that needs generating using your chosen template engine -2. `$data`: Any data that was supplied to the [`Write-PodeViewResponse`](../../../Functions/Responses/Write-PodeViewResponse) function +2. `$data`: Any data that was supplied to the [`Write-PodeViewResponse`](../../../Functions/Responses/Write-PodeViewResponse) function ## EPS From a794a34b483016ecdc4926f99797f7ae741ebedb Mon Sep 17 00:00:00 2001 From: Matthew Kelly Date: Sun, 1 Nov 2020 17:46:38 +0000 Subject: [PATCH 4/4] #618: minor cleanup --- examples/web-pages.ps1 | 2 -- src/Private/Logging.ps1 | 3 --- src/Private/ServiceServer.ps1 | 3 +-- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/examples/web-pages.ps1 b/examples/web-pages.ps1 index b17e96e85..389ac9c3e 100644 --- a/examples/web-pages.ps1 +++ b/examples/web-pages.ps1 @@ -32,13 +32,11 @@ Start-PodeServer -Threads 2 { Set-PodeViewEngine -Type Pode # wire up a custom logger - #TODO: can we remove this param, for a "$LogItem"? $logType = New-PodeLoggingMethod -Custom -ScriptBlock { param($item) $item.HttpMethod | Out-Default } - #TODO: can we remove this param, for a "$LogItem"? $logType | Add-PodeLogger -Name 'custom' -ScriptBlock { param($item) return @{ diff --git a/src/Private/Logging.ps1 b/src/Private/Logging.ps1 index dc59de6f8..b5760a450 100644 --- a/src/Private/Logging.ps1 +++ b/src/Private/Logging.ps1 @@ -297,7 +297,6 @@ function Start-PodeLoggingRunspace } # convert to log item into a writable format - #TODO: "$LogItem" ? $_args = @($log.Item) + @($logger.Arguments) if ($null -ne $logger.UsingVariables) { $_args = @($logger.UsingVariables.Value) + $_args @@ -326,7 +325,6 @@ function Start-PodeLoggingRunspace # send the writable log item off to the log writer if ($null -ne $result) { - #TODO: "$LogItem" ? $_args = @(,$result) + @($logger.Method.Arguments) if ($null -ne $logger.Method.UsingVariables) { $_args = @($logger.Method.UsingVariables.Value) + $_args @@ -357,7 +355,6 @@ function Test-PodeLoggerBatches $result = $batch.Items $batch.Items = @() - #TODO: "$LogItem" ? $_args = @(,$result) + @($logger.Method.Arguments) if ($null -ne $logger.Method.UsingVariables) { $_args = @($logger.Method.UsingVariables.Value) + $_args diff --git a/src/Private/ServiceServer.ps1 b/src/Private/ServiceServer.ps1 index 66c2196bd..7e60370f0 100644 --- a/src/Private/ServiceServer.ps1 +++ b/src/Private/ServiceServer.ps1 @@ -24,8 +24,7 @@ function Start-PodeServiceServer foreach ($name in $handlers.Keys) { $handler = $handlers[$name] - #TODO: Remove $ServiceEvent from args - $_args = @($ServiceEvent) + @($handler.Arguments) + $_args = @($handler.Arguments) if ($null -ne $handler.UsingVariables) { $_args = @($handler.UsingVariables.Value) + $_args }