-
-
Notifications
You must be signed in to change notification settings - Fork 90
/
Sessions.ps1
396 lines (326 loc) · 10.2 KB
/
Sessions.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
function New-PodeSession
{
$sid = @{
Name = $PodeContext.Server.Sessions.Name
Id = (Invoke-PodeScriptBlock -ScriptBlock $PodeContext.Server.Sessions.GenerateId -Return)
Properties = $PodeContext.Server.Sessions.Info
Data = @{}
}
Set-PodeSessionDataHash -Session $sid
$sid.Properties.TimeStamp = [DateTime]::UtcNow
return $sid
}
function ConvertTo-PodeSessionStrictSecret
{
param(
[Parameter(Mandatory=$true)]
[string]
$Secret
)
return "$($Secret);$($WebEvent.Request.UserAgent);$($WebEvent.Request.RemoteEndPoint.Address.IPAddressToString)"
}
function Set-PodeSession
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[hashtable]
$Session
)
$secure = [bool]($Session.Properties.Secure)
$strict = [bool]($Session.Properties.Strict)
$discard = [bool]($Session.Properties.Discard)
$httpOnly = [bool]($Session.Properties.HttpOnly)
$useHeaders = [bool]($Session.Properties.UseHeaders)
$secret = $PodeContext.Server.Sessions.Secret
# covert secret to strict mode
if ($strict) {
$secret = ConvertTo-PodeSessionStrictSecret -Secret $secret
}
# set session on header
if ($useHeaders) {
Set-PodeHeader -Name $Session.Name -Value $Session.Id -Secret $secret
}
# set session as cookie
else {
(Set-PodeCookie `
-Name $Session.Name `
-Value $Session.Id `
-Secret $secret `
-ExpiryDate (Get-PodeSessionExpiry -Session $Session) `
-HttpOnly:$httpOnly `
-Discard:$discard `
-Secure:$secure) | Out-Null
}
}
function Get-PodeSession
{
param (
[Parameter(Mandatory=$true)]
[hashtable]
$Session
)
$secret = $Session.Secret
$timestamp = [datetime]::UtcNow
$value = $null
$name = $Session.Name
# covert secret to strict mode
if ($Session.Info.Strict) {
$secret = ConvertTo-PodeSessionStrictSecret -Secret $secret
}
# session from header
if ($Session.Info.UseHeaders) {
# check that the header is validly signed
if (!(Test-PodeHeaderSigned -Name $Session.Name -Secret $secret)) {
return $null
}
# get the header from the request
$value = Get-PodeHeader -Name $Session.Name -Secret $secret
if ([string]::IsNullOrWhiteSpace($value)) {
return $null
}
}
# session from cookie
else {
# check that the cookie is validly signed
if (!(Test-PodeCookieSigned -Name $Session.Name -Secret $secret)) {
return $null
}
# get the cookie from the request
$cookie = Get-PodeCookie -Name $Session.Name -Secret $secret
if ([string]::IsNullOrWhiteSpace($cookie)) {
return $null
}
# get details from cookie
$name = $cookie.Name
$value = $cookie.Value
$timestamp = $cookie.TimeStamp
if ($null -ne $timestamp) {
$timestamp = $timestamp.ToUniversalTime()
}
}
# generate the session data
$data = @{
Name = $name
Id = $value
Properties = $Session.Info
Data = @{}
}
$data.Properties.TimeStamp = $timeStamp
return $data
}
function Revoke-PodeSession
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[hashtable]
$Session
)
# remove from cookie
if (!$Session.Properties.UseHeaders) {
Remove-PodeCookie -Name $Session.Name
}
# remove session from store
Invoke-PodeScriptBlock -ScriptBlock $Session.Delete -Arguments @($Session) -Splat
# blank the session
$Session.Clear()
}
function Set-PodeSessionDataHash
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[hashtable]
$Session
)
if (($null -eq $Session.Data) -or ($Session.Data.Count -eq 0)) {
$Session.Data = @{}
}
$Session.DataHash = (Invoke-PodeSHA256Hash -Value ($Session.Data.Clone() | ConvertTo-Json -Depth 10 -Compress))
}
function Test-PodeSessionDataHash
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[hashtable]
$Session
)
if ([string]::IsNullOrWhiteSpace($Session.DataHash)) {
return $false
}
if (($null -eq $Session.Data) -or ($Session.Data.Count -eq 0)) {
$Session.Data = @{}
}
$hash = (Invoke-PodeSHA256Hash -Value ($Session.Data | ConvertTo-Json -Depth 10 -Compress))
return ($Session.DataHash -eq $hash)
}
function Get-PodeSessionExpiry
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[hashtable]
$Session
)
if ($null -eq $Session.Properties) {
return [DateTime]::MinValue
}
$expiry = [DateTime]::UtcNow
if (!([bool]$Session.Properties.Extend)) {
$expiry = $Session.Properties.TimeStamp
if ($null -ne $expiry) {
$expiry = $expiry.ToUniversalTime()
}
}
$expiry = $expiry.AddSeconds($Session.Properties.Duration)
return $expiry
}
function Set-PodeSessionHelpers
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNull()]
[hashtable]
$Session
)
# force save a session's data to the store
$Session | Add-Member -MemberType NoteProperty -Name Save -Value {
param($session, $check)
# do nothing if session has no ID
if ([string]::IsNullOrWhiteSpace($session.Id)) {
return
}
# only save if check and hashes different, but not if extending expiry
if (!$session.Properties.Extend -and $check -and (Test-PodeSessionDataHash -Session $session)) {
return
}
# generate the expiry
$expiry = (Get-PodeSessionExpiry -Session $session)
# save session data to store
Invoke-PodeScriptBlock -ScriptBlock $PodeContext.Server.Sessions.Store.Set -Arguments @($session.Id, $session.Data, $expiry) -Splat
# update session's data hash
Set-PodeSessionDataHash -Session $session
}
# delete the current session
$Session | Add-Member -MemberType NoteProperty -Name Delete -Value {
param($session)
# remove data from store
Invoke-PodeScriptBlock -ScriptBlock $PodeContext.Server.Sessions.Store.Delete -Arguments $session.Id
# clear session
$session.Clear()
}
}
function Get-PodeSessionInMemStore
{
$store = New-Object -TypeName psobject
# add in-mem storage
$store | Add-Member -MemberType NoteProperty -Name Memory -Value @{}
# delete a sessionId and data
$store | Add-Member -MemberType NoteProperty -Name Delete -Value {
param($sessionId)
$PodeContext.Server.Sessions.Store.Memory.Remove($sessionId) | Out-Null
}
# get a sessionId's data
$store | Add-Member -MemberType NoteProperty -Name Get -Value {
param($sessionId)
$s = $PodeContext.Server.Sessions.Store.Memory[$sessionId]
# if expire, remove
if (($null -ne $s) -and ($s.Expiry -lt [DateTime]::UtcNow)) {
$PodeContext.Server.Sessions.Store.Memory.Remove($sessionId) | Out-Null
return $null
}
return $s.Data
}
# update/insert a sessionId and data
$store | Add-Member -MemberType NoteProperty -Name Set -Value {
param($sessionId, $data, $expiry)
$PodeContext.Server.Sessions.Store.Memory[$sessionId] = @{
Data = $data
Expiry = $expiry
}
}
return $store
}
function Set-PodeSessionInMemClearDown
{
# don't setup if serverless - as memory is short lived anyway
if ($PodeContext.Server.IsServerless) {
return
}
# cleardown expired inmem session every 10 minutes
Add-PodeSchedule -Name '__pode_session_inmem_cleanup__' -Cron '0/10 * * * *' -ScriptBlock {
$store = $PodeContext.Server.Sessions.Store
if (Test-PodeIsEmpty $store.Memory) {
return
}
# remove sessions that have expired
$now = [DateTime]::UtcNow
foreach ($key in $store.Memory.Keys) {
if ($store.Memory[$key].Expiry -lt $now) {
$store.Memory.Remove($key)
}
}
}
}
function Test-PodeSessionsConfigured
{
return (($null -ne $PodeContext.Server.Sessions) -and ($PodeContext.Server.Sessions.Count -gt 0))
}
function Get-PodeSessionData
{
param(
[Parameter()]
[string]
$SessionId
)
return (Invoke-PodeScriptBlock -ScriptBlock $PodeContext.Server.Sessions.Store.Get -Arguments $SessionId -Return)
}
function Get-PodeSessionMiddleware
{
return {
# if session already set, return
if ($WebEvent.Session) {
return $true
}
try
{
# get the session from cookie/header
$WebEvent.Session = Get-PodeSession -Session $PodeContext.Server.Sessions
# if no session found, create a new one on the current web event
if (!$WebEvent.Session) {
$WebEvent.Session = (New-PodeSession)
$new = $true
}
# get the session's data
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 {
$WebEvent.Session = (New-PodeSession)
$new = $true
}
# add helper methods to session
Set-PodeSessionHelpers -Session $WebEvent.Session
# add session to response if it's new or extendible
if ($new -or $WebEvent.Session.Properties.Extend) {
Set-PodeSession -Session $WebEvent.Session
}
# assign endware for session to set cookie/header
$WebEvent.OnEnd += @{
Logic = {
Save-PodeSession -Force
}
}
}
catch {
$_ | Write-PodeErrorLog
return $false
}
# move along
return $true
}
}