blib/lib/PAGI/Middleware/Session.pm

filter: Statementstmt 100% 116 / 116 Branchbran 96.6% 29 / 30 Conditioncond 74.2% 26 / 35 MC/DCmcdc 57.8% 11 / 19 Subroutinesub 100% 18 / 18 Podpod 50.0% 1 / 2 totaltotal 91.3% 201 / 220 CC 30 SCAR 16.3
CC
30
Cov
94%
__ANON__
8.0
_wrap_non_http
8.0
_init
7.0
CRAP 5.1
« blib/lib/PAGI/Middleware/RateLimit.pm ↑ Summary blib/lib/PAGI/Middleware/Cookie.pm »
1 package PAGI::Middleware::Session;
2 2 $PAGI::Middleware::Session::VERSION = '0.002002';
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use parent 'PAGI::Middleware';
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Future::AsyncAwait;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Digest::SHA qw(sha256_hex);
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 2 ▶use PAGI::Utils::Random qw(secure_random_bytes);
Subroutine BEGIN: called CC=1 SCAR=0.0
10  
11 =head1 NAME
12  
13 PAGI::Middleware::Session - Session management middleware with pluggable State/Store
14  
15 =head1 SYNOPSIS
16  
17 use PAGI::Middleware::Builder;
18  
19 # Default (cookie-based, in-memory store)
20 my $app = builder {
21 enable 'Session', secret => 'your-secret-key';
22 $my_app;
23 };
24  
25 # Explicit state and store
26 use PAGI::Middleware::Session::State::Header;
27 use PAGI::Middleware::Session::Store::Memory;
28  
29 my $app = builder {
30 enable 'Session',
31 secret => 'your-secret-key',
32 state => PAGI::Middleware::Session::State::Header->new(
33 header_name => 'X-Session-ID',
34 ),
35 store => PAGI::Middleware::Session::Store::Memory->new;
36 $my_app;
37 };
38  
39 # In your app:
40 async sub app {
41 my ($scope, $receive, $send) = @_;
42  
43 # Raw hashref access
44 my $session = $scope->{'pagi.session'};
45 $session->{user_id} = 123;
46  
47 # Or use the PAGI::Session helper
48 use PAGI::Session;
49 my $s = PAGI::Session->new($scope);
50 $s->set('user_id', 123);
51 my $uid = $s->get('user_id'); # dies if key missing
52 }
53  
54 =head1 DESCRIPTION
55  
56 PAGI::Middleware::Session provides server-side session management with a
57 pluggable architecture for session ID transport (State) and session data
58 storage (Store).
59  
60 The B<State> layer controls how the session ID travels between client and
61 server (cookies, headers, bearer tokens, or custom logic). The B<Store>
62 layer controls where session data is persisted (memory, Redis, database).
63  
64 By default, sessions use cookie-based IDs and in-memory storage.
65  
66 B<Warning:> The default in-memory store is suitable for development and
67 single-process deployments only. Sessions are not shared between workers
68 and are lost on restart. For production multi-worker deployments, provide
69 a C<store> object backed by Redis, a database, or another shared storage.
70  
71 =head1 CONFIGURATION
72  
73 =over 4
74  
75 =item * secret (required)
76  
77 Secret key used for session ID generation.
78  
79 =item * expire (default: 3600)
80  
81 Session expiration time in seconds.
82  
83 =item * state (optional)
84  
85 A L<PAGI::Middleware::Session::State> object that implements C<extract($scope)>
86 and C<inject(\@headers, $id, \%options)>. If not provided, a
87 L<PAGI::Middleware::Session::State::Cookie> instance is created using
88 C<cookie_name>, C<cookie_options>, and C<expire>.
89  
90 =item * store (optional)
91  
92 A L<PAGI::Middleware::Session::Store> object that implements async C<get($id)>,
93 C<set($id, $data)>, and C<delete($id)>. If not provided, a
94 L<PAGI::Middleware::Session::Store::Memory> instance is created.
95  
96 =item * cookie_name (default: 'pagi_session')
97  
98 Name of the session cookie. Only used when C<state> defaults to
99 L<PAGI::Middleware::Session::State::Cookie>.
100  
101 =item * cookie_options (default: { httponly => 1, path => '/', samesite => 'Lax' })
102  
103 Options for the session cookie. Only used when C<state> defaults to
104 L<PAGI::Middleware::Session::State::Cookie>. For production HTTPS
105 deployments, add C<< secure => 1 >>.
106  
107 =back
108  
109 =head1 STATE CLASSES
110  
111 State classes control how the session ID is extracted from requests and
112 injected into responses. All implement the L<PAGI::Middleware::Session::State>
113 interface.
114  
115 =over 4
116  
117 =item L<PAGI::Middleware::Session::State::Cookie>
118  
119 Default. Reads the session ID from a request cookie and sets it via
120 C<Set-Cookie> on the response. Suitable for browser-based web applications.
121  
122 =item L<PAGI::Middleware::Session::State::Header>
123  
124 Reads the session ID from a custom HTTP header. Requires C<header_name>;
125 accepts an optional C<pattern> regex with a capture group. Injection is a
126 no-op (the client manages header-based transport).
127  
128 PAGI::Middleware::Session::State::Header->new(
129 header_name => 'X-Session-ID',
130 );
131  
132 =item L<PAGI::Middleware::Session::State::Bearer>
133  
134 Convenience subclass of State::Header that reads an opaque bearer token from
135 the C<Authorization: Bearer E<lt>tokenE<gt>> header. Intended for opaque
136 session tokens, B<not> JWTs. For JWT authentication, use
137 L<PAGI::Middleware::Auth::Bearer> instead.
138  
139 PAGI::Middleware::Session::State::Bearer->new();
140  
141 =item L<PAGI::Middleware::Session::State::Callback>
142  
143 Custom session ID transport using coderefs. Requires an C<extract> coderef;
144 accepts an optional C<inject> coderef (defaults to no-op).
145  
146 PAGI::Middleware::Session::State::Callback->new(
147 extract => sub { my ($scope) = @_; ... },
148 inject => sub { my ($headers, $id, $options) = @_; ... },
149 );
150  
151 =back
152  
153 =head1 STORE CLASSES
154  
155 Store classes control where session data is persisted. All implement the
156 L<PAGI::Middleware::Session::Store> interface; methods return L<Future>
157 objects for async compatibility.
158  
159 =over 4
160  
161 =item L<PAGI::Middleware::Session::Store::Memory>
162  
163 Default. In-memory hash storage. Not shared across workers or restarts.
164 Suitable for development and testing only.
165  
166 =item External stores
167  
168 Redis, database, and other shared stores are available as separate CPAN
169 distributions. Any object implementing C<get($id)>, C<set($id, $data)>,
170 and C<delete($id)> (returning Futures) can be used.
171  
172 =back
173  
174 =head1 PAGI::Session HELPER
175  
176 L<PAGI::Session> is a standalone helper object that wraps the session
177 data with a clean accessor interface.
178  
179 use PAGI::Session;
180 my $session = PAGI::Session->new($scope);
181  
182 Key methods:
183  
184 =over 4
185  
186 =item * C<get($key)> - Dies if the key does not exist (catches typos).
187  
188 =item * C<get($key, $default)> - Returns C<$default> for missing keys.
189  
190 =item * C<set($key, $value)> - Sets a session value.
191  
192 =item * C<exists($key)> - Checks key existence.
193  
194 =item * C<delete($key)> - Removes a key.
195  
196 =item * C<keys> - Lists user keys (excludes internal C<_>-prefixed keys).
197  
198 =item * C<id> - Returns the session ID.
199  
200 =item * C<regenerate> - Requests session ID regeneration on next response.
201  
202 =item * C<destroy> - Marks the session for deletion.
203  
204 =back
205  
206 The helper stores a reference to the underlying hash, so mutations are
207 visible to the middleware.
208  
209 =head1 IDEMPOTENCY
210  
211 The middleware skips processing if C<< $scope-E<gt>{'pagi.session'} >>
212 already exists. This prevents double-initialization when the middleware
213 appears more than once in a stack.
214  
215 For mixed auth patterns (e.g. web cookies for browsers, bearer tokens for
216 APIs), use L<PAGI::Middleware::Session::State::Callback> with fallback
217 logic instead of stacking multiple Session middleware instances:
218  
219 use PAGI::Middleware::Session::State::Callback;
220 use PAGI::Middleware::Session::State::Cookie;
221 use PAGI::Middleware::Session::State::Bearer;
222  
223 my $cookie_state = PAGI::Middleware::Session::State::Cookie->new(
224 cookie_name => 'pagi_session',
225 expire => 3600,
226 );
227 my $bearer_state = PAGI::Middleware::Session::State::Bearer->new();
228  
229 enable 'Session',
230 secret => $ENV{SESSION_SECRET},
231 state => PAGI::Middleware::Session::State::Callback->new(
232 extract => sub {
233 my ($scope) = @_;
234 return $bearer_state->extract($scope)
235 // $cookie_state->extract($scope);
236 },
237 inject => sub {
238 my ($headers, $id, $options) = @_;
239 $cookie_state->inject($headers, $id, $options);
240 },
241 );
242  
243 =head1 NON-HTTP SCOPES (WebSocket, SSE, ...)
244  
245 If there is a session, WebSocket and SSE connections see it too: a scope
246 whose C<type> is not C<'http'> but which still carries a C<headers> key --
247 both a WebSocket upgrade request and an SSE request are typed this way (see
248 L<PAGI::Context>'s C<is_websocket>/C<is_sse>; SSE is its own distinct scope
249 C<type>, not C<'http'> plus a flag) -- gets a B<read-only> session: the
250 same C<state-E<gt>extract> + C<store-E<gt>get> lookup the C<'http'> path
251 uses, populating C<< $scope->{'pagi.session'} >> (and
252 C<< $scope->{'pagi.session_id'} >>, when a real session was found) before
253 calling the wrapped app. This is store-agnostic -- it works with whatever
254 C<store>/C<state> pair the middleware was configured with, not just
255 cookie-backed setups -- and scope-type-agnostic: any current or future
256 scope type with a C<headers> key gets the same treatment, WebSocket and SSE
257 are simply the two named, tested cases today.
258  
259 B<Nothing is ever saved.> There is no C<http.response.start>-shaped event on
260 a protocol upgrade to hook a save onto, so C<< store->set >> is never called
261 and no transport (e.g. C<Set-Cookie>) is ever injected for one of these
262 scopes. Any mutation an application makes to the session hashref during a
263 WebSocket/SSE connection is visible for the lifetime of that connection and
264 then silently discarded -- it never reaches the store and is never seen
265 again, by this connection or any other. Establish or change session state
266 (login, logout, regeneration) over a regular C<'http'> request; treat a
267 non-http scope's session as read-only.
268  
269 A session id that resolves to nothing (absent, malformed, or expired)
270 populates C<< $scope->{'pagi.session'} >> with an explicit empty hashref
271 C<{}> rather than leaving the key missing -- every C<'http'> request is
272 guaranteed a usable session (even a brand new, never-before-seen one falls
273 through to a freshly created hashref), so application code written against
274 that guarantee (e.g. anything that unconditionally builds a
275 L<PAGI::Session> from the scope) sees the same guarantee here instead of
276 having to special-case "no session key at all" for non-http scopes.
277 C<< $scope->{'pagi.session_id'} >> is left unset in this case -- there is no
278 real session id to report, and fabricating one for a hashref that was never
279 loaded from (or will ever be saved to) the store would be misleading.
280  
281 A scope with no C<headers> key at all (a C<lifespan> scope, which carries
282 no request to extract a session id from) is passed through completely
283 unmodified, exactly as every scope type other than C<'http'> always was
284 before this feature existed.
285  
286 =cut
287  
288 22 ▶sub _init {
Subroutine _init: called CC=7 SCAR=19.5
289 22 my ($self, $config) = @_;
290  
291 $self->{secret} = $config->{secret}
292 22 ▶ // die "Session middleware requires 'secret' option";
Condition50%1/2
$config->{"secret"} // die("Session middleware requires 'secret' option")
l!l
220
MC/DC0%0/1
$config->{"secret"} // die("Session middleware requires 'secret' option")
$config->{"secret"}
Truth table50%1/2
A
A= $config->{"secret"}
Aresult
11
00
293 22 ▶ $self->{expire} = $config->{expire} // 3600;
Condition100%2/2
$config->{"expire"} // 3600
l!l
121
MC/DC100%1/1
$config->{"expire"} // 3600
$config->{"expire"}
Truth table100%2/2
A
A= $config->{"expire"}
Aresult
11
00
294 22 $self->{_json} = JSON::MaybeXS->new(canonical => 1);
295  
296 # State: pluggable session ID transport
297 22 ▶ if ($config->{state}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'state'}) { } 2 20 22
298 2 $self->{state} = $config->{state};
299 } else {
300 20 require PAGI::Middleware::Session::State::Cookie;
301 $self->{state} = PAGI::Middleware::Session::State::Cookie->new(
302 cookie_name => $config->{cookie_name} // 'pagi_session',
303 cookie_options => $config->{cookie_options} // {
304 httponly => 1,
305 path => '/',
306 samesite => 'Lax',
307 },
308 expire => $self->{expire},
309 20 ▶ );
Condition75%3/4
$config->{"cookie_name"} // "pagi_session"
l!l
020
$config->{"cookie_options"} // {"httponly", 1, "path", "/", "samesite", "Lax"}
l!l
119
MC/DC0%0/1
$config->{"cookie_name"} // "pagi_session"
$config->{"cookie_name"}
MC/DC100%1/1
$config->{"cookie_options"} // {"httponly", 1, "path", "/", "samesite", "Lax"}
$config->{"cookie_options"}
Truth table50%1/2
A
A= $config->{"cookie_name"}
Aresult
11
00
Truth table100%2/2
A
A= $config->{"cookie_options"}
Aresult
11
00
310 }
311  
312 # Store: pluggable async session storage
313 22 ▶ if ($config->{store}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($config->{'store'}) { } 3 19 22
314 3 $self->{store} = $config->{store};
315 } else {
316 19 require PAGI::Middleware::Session::Store::Memory;
317 19 $self->{store} = PAGI::Middleware::Session::Store::Memory->new();
318 }
319 }
320  
321 41 ▶sub wrap {
Subroutine wrap: called CC=1 SCAR=0.0
Pod documented
322 41 my ($self, $app) = @_;
323  
324 41 ▶ return async sub {
Subroutine __ANON__: called CC=4 SCAR=13.9
325 41 my ($scope, $receive, $send) = @_;
326  
327 # Idempotency: skip if session already exists in scope. Checked
328 # before the type/headers branch below, so it now applies uniformly
329 # regardless of scope type -- NOT "same as it always did": before
330 # the non-http read-only support this file added, a non-'http'
331 # scope returned (pass-through, no session at all) before this
332 # check was ever reached, so it was unreachable code for any
333 # non-http scope. This move is what MAKES it apply uniformly.
334 41 ▶ if (exists $scope->{'pagi.session'}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $scope->{"pagi.session"}) 1 40 41
335 warn "Session middleware: pagi.session already in scope, skipping\n"
336 1 ▶ if $ENV{PAGI_DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"PAGI_DEBUG"} 0 1 1
337 1 await $app->($scope, $receive, $send);
338 1 return;
339 }
340  
341 40 ▶ if ($scope->{type} ne 'http') {
Branch: 1 branch
BranchTrueFalseTotal
if ($scope->{"type"} ne "http") 8 32 40
342 8 return await $self->_wrap_non_http($scope, $receive, $send, $app);
343 }
344  
345 # Extract session ID via state handler
346 32 my $session_id = $self->{state}->extract($scope);
347  
348 # Validate and load session
349 32 my ($session, $is_new, $snapshot) = await $self->_load_or_create_session($session_id);
350 32 $session_id = $session->{_id};
351  
352 # Add session to scope
353 32 my $new_scope = $self->modify_scope($scope, {
354 'pagi.session' => $session,
355 'pagi.session_id' => $session_id,
356 });
357  
358 # Wrap send to save session and inject state
359 64 ▶ my $wrapped_send = async sub {
Subroutine __ANON__: called CC=8 SCAR=20.8
360 64 my ($event) = @_;
361 64 ▶ if ($event->{type} eq 'http.response.start') {
Branch: 1 branch
BranchTrueFalseTotal
if ($event->{"type"} eq "http.response.start") 32 32 64
362 32 ▶ my @headers = @{$event->{headers} // []};
Condition50%1/2
$event->{"headers"} // []
l!l
320
MC/DC0%0/1
$event->{"headers"} // []
$event->{"headers"}
Truth table50%1/2
A
A= $event->{"headers"}
Aresult
11
00
363  
364 32 ▶ if ($session->{_destroyed}) {
Branch: 2 branches
BranchTrueFalseTotal
if ($session->{'_destroyed'}) { } 1 31 32
elsif ($session->{'_regenerated'}) { } 2 29 31
365 # Destroy: delete from store, clear client state
366 1 await $self->{store}->delete($session_id);
367 1 $self->{state}->clear(\@headers);
368 }
369 elsif ($session->{_regenerated}) {
370 # Regenerate: new ID, delete old, save under new
371 2 my $old_id = $session_id;
372 2 $session_id = $self->_generate_session_id();
373 2 $session->{_id} = $session_id;
374 2 delete $session->{_regenerated};
375 2 await $self->{store}->delete($old_id);
376 2 my $transport = await $self->_save_session($session_id, $session);
377 2 $self->{state}->inject(\@headers, $transport, {});
378 }
379 else {
380 # Normal: save always; inject if new or the session's
381 # data changed since it was loaded (the transport for
382 # cookie-backed stores IS the data, so a stale client
383 # copy after mutation is a correctness bug, not just
384 # a missed refresh).
385 my $dirty = $is_new
386 || !defined($snapshot)
387 29 ▶ || $self->{_json}->encode($session) ne $snapshot;
Condition83%5/6
$is_new || !defined($snapshot) || $self->{'_json'}->encode($session) ne $snapshot
l!l&&r!l&&!r
2126
$is_new or not defined $snapshot
l!l&&r!l&&!r
2108
MC/DC66%2/3
$is_new || !defined($snapshot) || $self->{'_json'}->encode($session) ne $snapshot
$is_new not defined $snapshot $self->{'_json'}->encode($session) ne $snapshot
Truth table75%3/4
A or not(B) || C
A= $is_newB= not defined $snapshotC= $self->{'_json'}->encode($session) ne $snapshot
ABCresult
1XX1
01X1
0011
0000
388 29 my $transport = await $self->_save_session($session_id, $session);
389 29 ▶ if ($dirty) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dirty) 23 6 29
390 23 $self->{state}->inject(\@headers, $transport, {});
391 }
392 }
393  
394 32 await $send->({ %$event, headers => \@headers });
395 32 return;
396 }
397 32 await $send->($event);
398 32 };
399  
400 32 await $app->($new_scope, $receive, $wrapped_send);
401 41 };
402 }
403  
404 # READ-ONLY session support for a non-'http' scope (websocket, sse, ...):
405 # store-agnostic, using the SAME state->extract + store->get path the http
406 # branch above uses -- never the store->set/state->inject halves, since
407 # there is no http.response.start-shaped channel on a protocol upgrade to
408 # hook a save onto. A scope with no 'headers' key at all (lifespan -- there
409 # is no request to extract a session id FROM) gets the original unconditional
410 # pass-through, preserved exactly.
411 #
412 # A found, unexpired session is loaded as-is (real 'pagi.session_id'
413 # included) so a consumer sees precisely what an HTTP request presenting
414 # the same cookie/header would have seen. A miss (no id presented, or an
415 # id that doesn't resolve/has expired) gets an EXPLICIT EMPTY hashref, not
416 # a missing key and not a freshly minted real session -- see this method's
417 # own POD-documented rationale: every 'http' request is guaranteed a usable
418 # $scope->{'pagi.session'} (even brand new, unauthenticated ones fall
419 # through to _load_or_create_session's own "create new" branch), so a
420 # consumer written against that guarantee (e.g. code that unconditionally
421 # calls PAGI::Session->new($scope)) must see the same guarantee here rather
422 # than an absent key it was never taught to check for. Fabricating a real
423 # session identity for a connection that presented none would be actively
424 # misleading, so the miss case gets {} with no '_id'/'_created' metadata,
425 # and 'pagi.session_id' is simply never added to scope in that case.
426 #
427 # Mutations an app makes to either the loaded or empty hashref during the
428 # connection are NEVER persisted anywhere: nothing here ever calls
429 # store->set, and there is no response event to carry a fresh transport
430 # even if there were. See this method's own SCOPE EXTENSIONS POD note.
431 8 ▶async sub _wrap_non_http {
Subroutine _wrap_non_http: called CC=8 SCAR=20.8
432 8 my ($self, $scope, $receive, $send, $app) = @_;
433  
434 8 ▶ unless (exists $scope->{headers}) {
Branch: 1 branch
BranchTrueFalseTotal
unless (exists $scope->{"headers"}) 1 7 8
435 1 await $app->($scope, $receive, $send);
436 1 return;
437 }
438  
439 7 my $session_id = $self->{state}->extract($scope);
440 7 my $session;
441 7 ▶ if (defined $session_id && length $session_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $session_id and length $session_id) 5 2 7
Condition66%2/3
defined $session_id and length $session_id
!ll&&!rl&&r
205
MC/DC50%1/2
defined $session_id and length $session_id
defined $session_id length $session_id
Truth table66%2/3
A and B
A= defined $session_idB= length $session_id
ABresult
0X0
100
111
442 5 my $loaded = await $self->_get_session($session_id);
443 5 ▶ $session = $loaded if $loaded && !$self->_is_expired($loaded);
Branch: 1 branch
BranchTrueFalseTotal
if $loaded and not $self->_is_expired($loaded) 2 3 5
Condition100%3/3
$loaded and not $self->_is_expired($loaded)
!ll&&!rl&&r
212
MC/DC100%2/2
$loaded and not $self->_is_expired($loaded)
$loaded not $self->_is_expired($loaded)
Truth table100%3/3
A and not(B)
A= $loadedB= not $self->_is_expired($loaded)
ABresult
0X0
100
111
444 }
445 7 ▶ $session //= {};
Condition100%2/2
$session //= {}
l!l
25
MC/DC100%1/1
$session //= {}
$session
Truth table100%2/2
A
A= $session
Aresult
11
00
446  
447 my $new_scope = $self->modify_scope($scope, {
448 'pagi.session' => $session,
449 7 ▶ (exists $session->{_id} ? ('pagi.session_id' => $session->{_id}) : ()),
Branch: 1 branch
BranchTrueFalseTotal
exists $session->{'_id'} ? : 2 5 7
450 });
451  
452 7 await $app->($new_scope, $receive, $send);
453 7 return;
454 2 }
455  
456 32 ▶async sub _load_or_create_session {
Subroutine _load_or_create_session: called CC=5 SCAR=16.1
457 32 my ($self, $session_id) = @_;
458  
459 # Try to load existing session. The store handles validation —
460 # server-side stores return undef for unknown IDs, cookie stores
461 # return undef if decoding/verification fails.
462 32 ▶ if (defined $session_id && length $session_id) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $session_id and length $session_id) 14 18 32
Condition66%2/3
defined $session_id and length $session_id
!ll&&!rl&&r
18014
MC/DC50%1/2
defined $session_id and length $session_id
defined $session_id length $session_id
Truth table66%2/3
A and B
A= defined $session_idB= length $session_id
ABresult
0X0
100
111
463 14 my $session = await $self->_get_session($session_id);
464 14 ▶ if ($session && !$self->_is_expired($session)) {
Branch: 1 branch
BranchTrueFalseTotal
if ($session and not $self->_is_expired($session)) 11 3 14
Condition100%3/3
$session and not $self->_is_expired($session)
!ll&&!rl&&r
2111
MC/DC100%2/2
$session and not $self->_is_expired($session)
$session not $self->_is_expired($session)
Truth table100%3/3
A and not(B)
A= $sessionB= not $self->_is_expired($session)
ABresult
0X0
100
111
465 11 $session->{_last_access} = time();
466 11 return ($session, 0, $self->{_json}->encode($session));
467 }
468 }
469  
470 # Create new session
471 21 $session_id = $self->_generate_session_id();
472 21 my $session = {
473 _id => $session_id,
474 _created => time(),
475 _last_access => time(),
476 };
477  
478 21 return ($session, 1, undef);
479 2 }
480  
481 23 ▶sub _generate_session_id {
Subroutine _generate_session_id: called CC=1 SCAR=0.0
482 23 my ($self) = @_;
483  
484 # Use cryptographically secure random bytes
485 23 my $random = unpack('H*', secure_random_bytes(16));
486 23 my $time = time();
487 23 return sha256_hex("$random-$time-$self->{secret}");
488 }
489  
490 19 ▶async sub _get_session {
Subroutine _get_session: called CC=1 SCAR=0.0
491 19 my ($self, $id) = @_;
492 19 return await $self->{store}->get($id);
493 2 }
494  
495 31 ▶async sub _save_session {
Subroutine _save_session: called CC=1 SCAR=0.0
496 31 my ($self, $id, $session) = @_;
497 31 return await $self->{store}->set($id, $session);
498 2 }
499  
500 15 ▶sub _is_expired {
Subroutine _is_expired: called CC=3 SCAR=12.5
501 15 my ($self, $session) = @_;
502  
503 15 ▶ my $last_access = $session->{_last_access} // $session->{_created} // 0;
Condition40%2/5
($session->{"_last_access"} // $session->{"_created"}) // 0
l!l
150
$session->{"_last_access"} // $session->{"_created"}
l!l&&r!l&&!r
1500
MC/DC0%0/2
($session->{"_last_access"} // $session->{"_created"}) // 0
$session->{"_last_access"} $session->{"_created"}
Truth table33%1/3
A // B
A= $session->{"_last_access"}B= $session->{"_created"}
ABresult
1X1
011
000
504 15 return (time() - $last_access) > $self->{expire};
505 }
506  
507 # Class method to clear all sessions (useful for testing)
508 7 ▶sub clear_sessions {
Subroutine clear_sessions: called CC=1 SCAR=0.0
Pod undocumented
509 7 require PAGI::Middleware::Session::Store::Memory;
510 7 PAGI::Middleware::Session::Store::Memory::clear_all();
511 }
512  
513 2 1;
514  
515 __END__
« blib/lib/PAGI/Middleware/RateLimit.pm ↑ Summary blib/lib/PAGI/Middleware/Cookie.pm »