Debian Codegraph @

lib/Dancer2/Core/Role/SessionFactory.pm

raw
1 package Dancer2::Core::Role::SessionFactory;
2 # ABSTRACT: Role for session factories
3 $Dancer2::Core::Role::SessionFactory::VERSION = '2.2.2';
4 use Moo::Role;
5 with 'Dancer2::Core::Role::Engine';
6
7 use Carp 'croak';
8 use Crypt::URandom ();
9 use Dancer2::Core::Session;
10 use Dancer2::Core::Types;
11 use MIME::Base64 'encode_base64url';
12 use Ref::Util qw< is_ref is_arrayref is_hashref >;
13
14 sub hook_aliases { +{} }
15 sub supported_hooks {
16 qw/
17 engine.session.before_retrieve
18 engine.session.after_retrieve
19
20 engine.session.before_create
21 engine.session.after_create
22
23 engine.session.before_change_id
24 engine.session.after_change_id
25
26 engine.session.before_destroy
27 engine.session.after_destroy
28
29 engine.session.before_flush
30 engine.session.after_flush
31 /;
32 }
33
34 sub _build_type {
35 'SessionFactory';
36 } # XXX vs 'Session'? Unused, so I can't tell -- xdg
37
38 has log_cb => (
39 is => 'ro',
40 isa => CodeRef,
41 default => sub { sub {1} },
42 );
43
44 has cookie_name => (
45 is => 'ro',
46 isa => Str,
47 default => sub {'dancer.session'},
48 );
49
50 has cookie_domain => (
51 is => 'ro',
52 isa => Str,
53 predicate => 1,
54 );
55
56 has cookie_path => (
57 is => 'ro',
58 isa => Str,
59 default => sub {"/"},
60 );
61
62 has cookie_duration => (
63 is => 'ro',
64 isa => Str,
65 predicate => 1,
66 );
67
68 has session_duration => (
69 is => 'ro',
70 isa => Num,
71 predicate => 1,
72 );
73
74 has is_secure => (
75 is => 'rw',
76 isa => Bool,
77 default => sub {0},
78 );
79
80 has is_http_only => (
81 is => 'rw',
82 isa => Bool,
83 default => sub {1},
84 );
85
86 has cookie_same_site => (
87 is => 'ro',
88 isa => Str,
89 predicate => 1,
90 coerce => sub { ucfirst $_[0] },
91 );
92
93 sub create {
94 my ($self) = @_;
95
96 my %args = ( id => $self->generate_id, );
97
98 $args{expires} = $self->cookie_duration
99 if $self->has_cookie_duration;
100
101 my $session = Dancer2::Core::Session->new(%args);
102
103 $self->execute_hook( 'engine.session.before_create', $session );
104
105 # XXX why do we _flush now? Seems unnecessary -- xdg, 2013-03-03
106 eval { $self->_flush( $session->id, $session->data ) };
107 croak "Unable to create a new session: $@"
108 if $@;
109
110 $self->execute_hook( 'engine.session.after_create', $session );
111 return $session;
112 }
113
114 # prepend epoch seconds so session ID is roughly monotonic
115 sub generate_id {
116 my ($self) = @_;
117
118 return encode_base64url(
119 pack( "Na*", time, Crypt::URandom::urandom(20) )
120 );
121 }
122
123 sub validate_id {
124 my ($self, $id) = @_;
125
126 return 0
127 if !defined $id || length($id) > 4096;
128
129 return $id =~ m/\A[A-Za-z0-9_\-~]+\z/;
130 }
131
132 requires '_retrieve';
133
134 sub retrieve {
135 my ( $self, %params ) = @_;
136 my $id = $params{id};
137
138 $self->execute_hook( 'engine.session.before_retrieve', $id );
139
140 my $data;
141 # validate format of session id before attempt to retrieve
142 my $rc = eval {
143 $self->validate_id($id) && ( $data = $self->_retrieve($id) );
144 };
145 croak "Unable to retrieve session with id '$id'"
146 if ! $rc;
147
148 my %args = ( id => $id, );
149
150 $args{data} = $data
151 if $data and is_hashref($data);
152
153 $args{expires} = $self->cookie_duration
154 if $self->has_cookie_duration;
155
156 my $session = Dancer2::Core::Session->new(%args);
157
158 $self->execute_hook( 'engine.session.after_retrieve', $session );
159 return $session;
160 }
161
162 # XXX eventually we could perhaps require '_change_id'?
163
164 sub change_id {
165 my ( $self, %params ) = @_;
166 my $session = $params{session};
167 my $old_id = $session->id;
168
169 $self->execute_hook( 'engine.session.before_change_id', $old_id );
170
171 my $new_id = $self->generate_id;
172 $session->id( $new_id );
173
174 eval { $self->_change_id( $old_id, $new_id ) };
175 croak "Unable to change session id for session with id $old_id: $@"
176 if $@;
177
178 $self->execute_hook( 'engine.session.after_change_id', $new_id );
179 }
180
181 requires '_destroy';
182
183 sub destroy {
184 my ( $self, %params ) = @_;
185 my $id = $params{id};
186 $self->execute_hook( 'engine.session.before_destroy', $id );
187
188 eval { $self->_destroy($id) };
189 croak "Unable to destroy session with id '$id': $@"
190 if $@;
191
192 $self->execute_hook( 'engine.session.after_destroy', $id );
193 return $id;
194 }
195
196 requires '_flush';
197
198 sub flush {
199 my ( $self, %params ) = @_;
200 my $session = $params{session};
201 $self->execute_hook( 'engine.session.before_flush', $session );
202
203 eval { $self->_flush( $session->id, $session->data ) };
204 croak "Unable to flush session: $@"
205 if $@;
206
207 $self->execute_hook( 'engine.session.after_flush', $session );
208 return $session->id;
209 }
210
211 sub set_cookie_header {
212 my ( $self, %params ) = @_;
213 $params{response}->push_header(
214 'Set-Cookie',
215 $self->cookie( session => $params{session} )->to_header
216 );
217 }
218
219 sub cookie {
220 my ( $self, %params ) = @_;
221 my $session = $params{session};
222 croak "cookie() requires a valid 'session' parameter"
223 unless is_ref($session) && $session->isa("Dancer2::Core::Session");
224
225 my %cookie = (
226 value => $session->id,
227 name => $self->cookie_name,
228 path => $self->cookie_path,
229 secure => $self->is_secure,
230 http_only => $self->is_http_only,
231 );
232
233 $cookie{same_site} = $self->cookie_same_site
234 if $self->has_cookie_same_site;
235
236 $cookie{domain} = $self->cookie_domain
237 if $self->has_cookie_domain;
238
239 if ( my $expires = $session->expires ) {
240 $cookie{expires} = $expires;
241 }
242
243 return Dancer2::Core::Cookie->new(%cookie);
244 }
245
246 requires '_sessions';
247
248 sub sessions {
249 my ($self) = @_;
250 my $sessions = $self->_sessions;
251
252 croak "_sessions() should return an array ref"
253 unless is_arrayref($sessions);
254
255 return $sessions;
256 }
257
258 1;
259
260 __END__
261
262 =pod
263
264 =encoding UTF-8
265
266 =head1 NAME
267
268 Dancer2::Core::Role::SessionFactory - Role for session factories
269
270 =head1 VERSION
271
272 version 2.2.2
273
274 =head1 DESCRIPTION
275
276 Any class that consumes this role will be able to store, create, retrieve and
277 destroy session objects.
278
279 The default values for attributes can be overridden in your Dancer2
280 configuration. See L<Dancer2::Config/Session-engine>.
281
282 =head1 ATTRIBUTES
283
284 =head2 cookie_name
285
286 The name of the cookie to create for storing the session key
287
288 Defaults to C<dancer.session>
289
290 =head2 cookie_domain
291
292 The domain of the cookie to create for storing the session key.
293 Defaults to the empty string and is unused as a result.
294
295 =head2 cookie_path
296
297 The path of the cookie to create for storing the session key.
298 Defaults to "/".
299
300 =head2 cookie_duration
301
302 Default duration before session cookie expiration. If set, the
303 L<Dancer2::Core::Session> C<expires> attribute will be set to the current time
304 plus this duration (expression parsed by L<Dancer2::Core::Time>).
305
306 =head2 cookie_same_site
307
308 Restricts the session cookie to a first-party or same-site context.
309 Defaults to the empty string and is unused as a result.
310 See L<Dancer2::Core::Cookie/same_site>.
311
312 =head2 session_duration
313
314 Duration in seconds before sessions should expire, regardless of cookie
315 expiration. If set, then SessionFactories should use this to enforce a limit
316 on session validity.
317
318 =head2 is_secure
319
320 Boolean flag to tell if the session cookie is secure or not.
321
322 Default is false.
323
324 =head2 is_http_only
325
326 Boolean flag to tell if the session cookie is http only.
327
328 Default is true.
329
330 =head1 INTERFACE
331
332 Following is the interface provided by this role. When specified the required
333 methods to implement are described.
334
335 =head2 create
336
337 Create a brand new session object and store it. Returns the newly created
338 session object.
339
340 Triggers an exception if the session is unable to be created.
341
342 my $session = MySessionFactory->create();
343
344 This method does not need to be implemented in the class.
345
346 =head2 generate_id
347
348 Returns a randomly-generated, guaranteed-unique string.
349 By default, it is a 32-character, URL-safe, Base64 encoded combination
350 of a 32 bit timestamp and 160 bits of random data generated by the
351 operating system's cryptographic random number generator via
352 L<Crypt::URandom>.
353 The timestamp ensures that session IDs are generally monotonic.
354
355 This method is used internally by create() to set the session ID.
356
357 This method does not need to be implemented in the class unless an
358 alternative method for session ID generation is desired.
359
360 =head2 validate_id
361
362 Returns true if a session id is of the correct format, or false otherwise.
363
364 By default, this ensures that the session ID is a string of characters
365 from the Base64 schema for "URL Applications" plus the C<~> character,
366 and no longer than 4096 characters. The length limit corresponds to the
367 maximum size of an HTTP cookie, so it accommodates cookie-based session
368 engines such as L<Dancer2::Session::Cookie> while rejecting oversized
369 values that would otherwise be handed to the backend unchanged.
370
371 This method does not need to be implemented in the class unless an
372 alternative set of characters for session IDs is desired.
373
374 =head2 retrieve
375
376 Return the session object corresponding to the session ID given. If none is
377 found, triggers an exception.
378
379 my $session = MySessionFactory->retrieve(id => $id);
380
381 The method C<_retrieve> must be implemented. It must take C<$id> as a single
382 argument and must return a hash reference of session data.
383
384 =head2 change_id
385
386 Changes the session ID of the corresponding session.
387
388 MySessionFactory->change_id(session => $session_object);
389
390 The method C<_change_id> must be implemented. It must take C<$old_id> and
391 C<$new_id> as arguments and change the ID from the old one to the new one
392 in the underlying session storage.
393
394 =head2 destroy
395
396 Purges the session object that matches the ID given. Returns the ID of the
397 destroyed session if succeeded, triggers an exception otherwise.
398
399 MySessionFactory->destroy(id => $id);
400
401 The C<_destroy> method must be implemented. It must take C<$id> as a single
402 argument and destroy the underlying data.
403
404 =head2 flush
405
406 Make sure the session object is stored in the factory's backend. This method is
407 called to notify the backend about the change in the session object.
408
409 The Dancer application will not call flush unless the session C<is_dirty>
410 attribute is true to avoid unnecessary writes to the database when no
411 data has been modified.
412
413 An exception is triggered if the session is unable to be updated in the backend.
414
415 MySessionFactory->flush(session => $session);
416
417 The C<_flush> method must be implemented. It must take two arguments: the C<$id>
418 and a hash reference of session data.
419
420 =head2 set_cookie_header
421
422 Sets the session cookie into the response object
423
424 MySessionFactory->set_cookie_header(
425 response => $response,
426 session => $session,
427 destroyed => undef,
428 );
429
430 The C<response> parameter contains a L<Dancer2::Core::Response> object.
431 The C<session> parameter contains a L<Dancer2::Core::Session> object.
432
433 The C<destroyed> parameter is optional. If true, it indicates the
434 session was marked destroyed by the request context. The default
435 C<set_cookie_header> method doesn't need that information, but it is
436 included in case a SessionFactory must handle destroyed sessions
437 differently (such as signalling to middleware).
438
439 =head2 cookie
440
441 Coerce a session object into a L<Dancer2::Core::Cookie> object.
442
443 MySessionFactory->cookie(session => $session);
444
445 =head2 sessions
446
447 Return a list of all session IDs stored in the backend.
448 Useful to create cleaning scripts, in conjunction with session's creation time.
449
450 The C<_sessions> method must be implemented. It must return an array reference
451 of session IDs (or an empty array reference).
452
453 =head1 CONFIGURATION
454
455 If there are configuration values specific to your session factory in your config.yml or
456 environment, those will be passed to the constructor of the session factory automatically.
457 In order to accept and store them, you need to define accessors for them.
458
459 engines:
460 session:
461 Example:
462 database_connection: "some_data"
463
464 In your session factory:
465
466 package Dancer2::Session::Example;
467 use Moo;
468 with "Dancer2::Core::Role::SessionFactory";
469
470 has database_connection => ( is => "ro" );
471
472 You need to do this for every configuration key. The ones that do not have accessors
473 defined will just go to the void.
474
475 =head1 AUTHOR
476
477 Dancer Core Developers
478
479 =head1 COPYRIGHT AND LICENSE
480
481 This software is copyright (c) 2026 by Alexis Sukrieh.
482
483 This is free software; you can redistribute it and/or modify it under
484 the same terms as the Perl 5 programming language system itself.
485
486 =cut