Updated POD
[catagits/Catalyst-Plugin-Session.git] / lib / Catalyst / Plugin / Session.pm
1 #!/usr/bin/perl
2
3 package Catalyst::Plugin::Session;
4
5 use Moose;
6 with 'MooseX::Emulate::Class::Accessor::Fast';
7 use MRO::Compat;
8 use Catalyst::Exception ();
9 use Digest              ();
10 use overload            ();
11 use Object::Signature   ();
12 use Carp;
13 use List::Util qw/ max /;
14
15 use namespace::clean -except => 'meta';
16
17 our $VERSION = '0.37';
18 $VERSION = eval $VERSION;
19
20 my @session_data_accessors; # used in delete_session
21
22 __PACKAGE__->mk_accessors(
23         "_session_delete_reason",
24         @session_data_accessors = qw/
25           _sessionid
26           _session
27           _session_expires
28           _extended_session_expires
29           _session_data_sig
30           _flash
31           _flash_keep_keys
32           _flash_key_hashes
33           _tried_loading_session_id
34           _tried_loading_session_data
35           _tried_loading_session_expires
36           _tried_loading_flash_data
37           /
38 );
39
40 sub _session_plugin_config {
41     my $c = shift;
42     # FIXME - Start warning once all the state/store modules have also been updated.
43     #$c->log->warn("Deprecated 'session' config key used, please use the key 'Plugin::Session' instead")
44     #    if exists $c->config->{session}
45     #$c->config->{'Plugin::Session'} ||= delete($c->config->{session}) || {};
46     $c->config->{'Plugin::Session'} ||= $c->config->{session} || {};
47 }
48
49 sub setup {
50     my $c = shift;
51
52     $c->maybe::next::method(@_);
53
54     $c->check_session_plugin_requirements;
55     $c->setup_session;
56
57     return $c;
58 }
59
60 sub check_session_plugin_requirements {
61     my $c = shift;
62
63     unless ( $c->isa("Catalyst::Plugin::Session::State")
64         && $c->isa("Catalyst::Plugin::Session::Store") )
65     {
66         my $err =
67           (     "The Session plugin requires both Session::State "
68               . "and Session::Store plugins to be used as well." );
69
70         $c->log->fatal($err);
71         Catalyst::Exception->throw($err);
72     }
73 }
74
75 sub setup_session {
76     my $c = shift;
77
78     my $cfg = $c->_session_plugin_config;
79
80     %$cfg = (
81         expires        => 7200,
82         verify_address => 0,
83         verify_user_agent => 0,
84         expiry_threshold => 0,
85         %$cfg,
86     );
87
88     $c->maybe::next::method();
89 }
90
91 sub prepare_action {
92     my $c = shift;
93
94     $c->maybe::next::method(@_);
95
96     if (    $c->_session_plugin_config->{flash_to_stash}
97         and $c->sessionid
98         and my $flash_data = $c->flash )
99     {
100         @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
101     }
102 }
103
104 sub finalize_headers {
105     my $c = shift;
106
107     # fix cookie before we send headers
108     $c->_save_session_expires;
109
110     # Force extension of session_expires before finalizing headers, so a pos
111     # up to date. First call to session_expires will extend the expiry, subs
112     # just return the previously extended value.
113     $c->session_expires;
114
115     return $c->maybe::next::method(@_);
116 }
117
118 sub finalize_body {
119     my $c = shift;
120
121     # We have to finalize our session *before* $c->engine->finalize_xxx is called,
122     # because we do not want to send the HTTP response before the session is stored/committed to
123     # the session database (or whatever Session::Store you use).
124     $c->finalize_session;
125
126     return $c->maybe::next::method(@_);
127 }
128
129 sub finalize_session {
130     my $c = shift;
131
132     $c->maybe::next::method(@_);
133
134     $c->_save_session_id;
135     $c->_save_session;
136     $c->_save_flash;
137
138     $c->_clear_session_instance_data;
139 }
140
141 sub _save_session_id {
142     my $c = shift;
143
144     # we already called set when allocating
145     # no need to tell the state plugins anything new
146 }
147
148 sub _save_session_expires {
149     my $c = shift;
150
151     if ( defined($c->_session_expires) ) {
152
153         if (my $sid = $c->sessionid) {
154
155             my $current  = $c->_get_stored_session_expires;
156             my $extended = $c->session_expires;
157             if ($extended > $current) {
158                 $c->store_session_data( "expires:$sid" => $extended );
159             }
160
161         }
162     }
163 }
164
165 sub _save_session {
166     my $c = shift;
167
168     if ( my $session_data = $c->_session ) {
169
170         no warnings 'uninitialized';
171         if ( Object::Signature::signature($session_data) ne
172             $c->_session_data_sig )
173         {
174             $session_data->{__updated} = time();
175             my $sid = $c->sessionid;
176             $c->store_session_data( "session:$sid" => $session_data );
177         }
178     }
179 }
180
181 sub _save_flash {
182     my $c = shift;
183
184     if ( my $flash_data = $c->_flash ) {
185
186         my $hashes = $c->_flash_key_hashes || {};
187         my $keep = $c->_flash_keep_keys || {};
188         foreach my $key ( keys %$hashes ) {
189             if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
190                 delete $flash_data->{$key};
191             }
192         }
193
194         my $sid = $c->sessionid;
195
196         my $session_data = $c->_session;
197         if (%$flash_data) {
198             $session_data->{__flash} = $flash_data;
199         }
200         else {
201             delete $session_data->{__flash};
202         }
203         $c->_session($session_data);
204         $c->_save_session;
205     }
206 }
207
208 sub _load_session_expires {
209     my $c = shift;
210     return $c->_session_expires if $c->_tried_loading_session_expires;
211     $c->_tried_loading_session_expires(1);
212
213     if ( my $sid = $c->sessionid ) {
214         my $expires =  $c->_get_stored_session_expires;
215
216         if ( $expires >= time() ) {
217             $c->_session_expires( $expires );
218             return $expires;
219         } else {
220             $c->delete_session( "session expired" );
221             return 0;
222         }
223     }
224
225     return;
226 }
227
228 sub _load_session {
229     my $c = shift;
230     return $c->_session if $c->_tried_loading_session_data;
231     $c->_tried_loading_session_data(1);
232
233     if ( my $sid = $c->sessionid ) {
234         if ( $c->_load_session_expires ) {    # > 0
235
236             my $session_data = $c->get_session_data("session:$sid") || return;
237             $c->_session($session_data);
238
239             no warnings 'uninitialized';    # ne __address
240             if (   $c->_session_plugin_config->{verify_address}
241                 && exists $session_data->{__address}
242                 && $session_data->{__address} ne $c->request->address )
243             {
244                 $c->log->warn(
245                         "Deleting session $sid due to address mismatch ("
246                       . $session_data->{__address} . " != "
247                       . $c->request->address . ")"
248                 );
249                 $c->delete_session("address mismatch");
250                 return;
251             }
252             if (   $c->_session_plugin_config->{verify_user_agent}
253                 && $session_data->{__user_agent} ne $c->request->user_agent )
254             {
255                 $c->log->warn(
256                         "Deleting session $sid due to user agent mismatch ("
257                       . $session_data->{__user_agent} . " != "
258                       . $c->request->user_agent . ")"
259                 );
260                 $c->delete_session("user agent mismatch");
261                 return;
262             }
263
264             $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
265             $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
266             $c->_expire_session_keys;
267
268             return $session_data;
269         }
270     }
271
272     return;
273 }
274
275 sub _load_flash {
276     my $c = shift;
277     return $c->_flash if $c->_tried_loading_flash_data;
278     $c->_tried_loading_flash_data(1);
279
280     if ( my $sid = $c->sessionid ) {
281
282         my $session_data = $c->session;
283         $c->_flash($session_data->{__flash});
284
285         if ( my $flash_data = $c->_flash )
286         {
287             $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
288
289             return $flash_data;
290         }
291     }
292
293     return;
294 }
295
296 sub _expire_session_keys {
297     my ( $c, $data ) = @_;
298
299     my $now = time;
300
301     my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
302     foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
303         delete $c->_session->{$key};
304         delete $expire_times->{$key};
305     }
306 }
307
308 sub _clear_session_instance_data {
309     my $c = shift;
310     $c->$_(undef) for @session_data_accessors;
311     $c->maybe::next::method(@_); # allow other plugins to hook in on this
312 }
313
314 sub change_session_id {
315     my $c = shift;
316
317     my $sessiondata = $c->session;
318     my $oldsid = $c->sessionid;
319     my $newsid = $c->create_session_id;
320
321     if ($oldsid) {
322         $c->log->debug(qq/change_sessid: deleting session data from "$oldsid"/) if $c->debug;
323         $c->delete_session_data("${_}:${oldsid}") for qw/session expires flash/;
324     }
325
326     $c->log->debug(qq/change_sessid: storing session data to "$newsid"/) if $c->debug;
327     $c->store_session_data( "session:$newsid" => $sessiondata );
328
329     return $newsid;
330 }
331
332 sub delete_session {
333     my ( $c, $msg ) = @_;
334
335     $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
336
337     # delete the session data
338     if ( my $sid = $c->sessionid ) {
339         $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
340         $c->delete_session_id($sid);
341     }
342
343     # reset the values in the context object
344     # see the BEGIN block
345     $c->_clear_session_instance_data;
346
347     $c->_session_delete_reason($msg);
348 }
349
350 sub session_delete_reason {
351     my $c = shift;
352
353     $c->session_is_valid; # check that it was loaded
354
355     $c->_session_delete_reason(@_);
356 }
357
358 sub session_expires {
359     my $c = shift;
360
361     if ( defined( my $expires = $c->_extended_session_expires ) ) {
362         return $expires;
363     } elsif ( defined( $expires = $c->_load_session_expires ) ) {
364         return $c->extend_session_expires( $expires );
365     } else {
366         return 0;
367     }
368 }
369
370 sub extend_session_expires {
371     my ( $c, $expires ) = @_;
372
373     my $threshold = $c->_session_plugin_config->{expiry_threshold} || 0;
374
375     if ( my $sid = $c->sessionid ) {
376         my $expires = $c->_get_stored_session_expires;
377         my $cutoff  = $expires - $threshold;
378
379         if (!$threshold || $cutoff <= time) {
380
381             $c->_extended_session_expires( my $updated = $c->calculate_initial_session_expires() );
382             $c->extend_session_id( $sid, $updated );
383
384             return $updated;
385
386         } else {
387
388             return $expires;
389
390         }
391
392     } else {
393
394         return;
395
396     }
397
398 }
399
400 sub change_session_expires {
401     my ( $c, $expires ) = @_;
402
403     $expires ||= 0;
404     my $sid = $c->sessionid;
405     my $time_exp = time() + $expires;
406     $c->store_session_data( "expires:$sid" => $time_exp );
407 }
408
409 sub _get_stored_session_expires {
410     my ($c) = @_;
411
412     if ( my $sid = $c->sessionid ) {
413         return $c->get_session_data("expires:$sid") || 0;
414     } else {
415         return 0;
416     }
417 }
418
419 sub initial_session_expires {
420     my $c = shift;
421     return ( time() + $c->_session_plugin_config->{expires} );
422 }
423
424 sub calculate_initial_session_expires {
425     my ($c) = @_;
426     return max( $c->initial_session_expires, $c->_get_stored_session_expires );
427 }
428
429 sub calculate_extended_session_expires {
430     my ( $c, $prev ) = @_;
431     return ( time() + $prev );
432 }
433
434 sub reset_session_expires {
435     my ( $c, $sid ) = @_;
436
437     my $exp = $c->calculate_initial_session_expires;
438     $c->_session_expires( $exp );
439     #
440     # since we're setting _session_expires directly, make load_session_expires
441     # actually use that value.
442     #
443     $c->_tried_loading_session_expires(1);
444     $c->_extended_session_expires( $exp );
445     $exp;
446 }
447
448 sub sessionid {
449     my $c = shift;
450
451     return $c->_sessionid || $c->_load_sessionid;
452 }
453
454 sub _load_sessionid {
455     my $c = shift;
456     return if $c->_tried_loading_session_id;
457     $c->_tried_loading_session_id(1);
458
459     if ( defined( my $sid = $c->get_session_id ) ) {
460         if ( $c->validate_session_id($sid) ) {
461             # temporarily set the inner key, so that validation will work
462             $c->_sessionid($sid);
463             return $sid;
464         } else {
465             my $err = "Tried to set invalid session ID '$sid'";
466             $c->log->error($err);
467             Catalyst::Exception->throw($err);
468         }
469     }
470
471     return;
472 }
473
474 sub session_is_valid {
475     my $c = shift;
476
477     # force a check for expiry, but also __address, etc
478     if ( $c->_load_session ) {
479         return 1;
480     } else {
481         return;
482     }
483 }
484
485 sub validate_session_id {
486     my ( $c, $sid ) = @_;
487
488     $sid and $sid =~ /^[a-f\d]+$/i;
489 }
490
491 sub session {
492     my $c = shift;
493
494     my $session = $c->_session || $c->_load_session || do {
495         $c->create_session_id_if_needed;
496         $c->initialize_session_data;
497     };
498
499     if (@_) {
500       my $new_values = @_ > 1 ? { @_ } : $_[0];
501       croak('session takes a hash or hashref') unless ref $new_values;
502
503       for my $key (keys %$new_values) {
504         $session->{$key} = $new_values->{$key};
505       }
506     }
507
508     $session;
509 }
510
511 sub keep_flash {
512     my ( $c, @keys ) = @_;
513     my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
514     (@{$href}{@keys}) = ((undef) x @keys);
515 }
516
517 sub _flash_data {
518     my $c = shift;
519     $c->_flash || $c->_load_flash || do {
520         $c->create_session_id_if_needed;
521         $c->_flash( {} );
522     };
523 }
524
525 sub _set_flash {
526     my $c = shift;
527     if (@_) {
528         my $items = @_ > 1 ? {@_} : $_[0];
529         croak('flash takes a hash or hashref') unless ref $items;
530         @{ $c->_flash }{ keys %$items } = values %$items;
531     }
532 }
533
534 sub flash {
535     my $c = shift;
536     $c->_flash_data;
537     $c->_set_flash(@_);
538     return $c->_flash;
539 }
540
541 sub clear_flash {
542     my $c = shift;
543
544     #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
545     $c->_flash_key_hashes({});
546     $c->_flash_keep_keys({});
547     $c->_flash({});
548 }
549
550 sub session_expire_key {
551     my ( $c, %keys ) = @_;
552
553     my $now = time;
554     @{ $c->session->{__expire_keys} }{ keys %keys } =
555       map { $now + $_ } values %keys;
556 }
557
558 sub initialize_session_data {
559     my $c = shift;
560
561     my $now = time;
562
563     return $c->_session(
564         {
565             __created => $now,
566             __updated => $now,
567
568             (
569                 $c->_session_plugin_config->{verify_address}
570                 ? ( __address => $c->request->address||'' )
571                 : ()
572             ),
573             (
574                 $c->_session_plugin_config->{verify_user_agent}
575                 ? ( __user_agent => $c->request->user_agent||'' )
576                 : ()
577             ),
578         }
579     );
580 }
581
582 sub generate_session_id {
583     my $c = shift;
584
585     my $digest = $c->_find_digest();
586     $digest->add( $c->session_hash_seed() );
587     return $digest->hexdigest;
588 }
589
590 sub create_session_id_if_needed {
591     my $c = shift;
592     $c->create_session_id unless $c->sessionid;
593 }
594
595 sub create_session_id {
596     my $c = shift;
597
598     my $sid = $c->generate_session_id;
599
600     $c->log->debug(qq/Created session "$sid"/) if $c->debug;
601
602     $c->_sessionid($sid);
603     $c->reset_session_expires;
604     $c->set_session_id($sid);
605
606     return $sid;
607 }
608
609 my $counter;
610
611 sub session_hash_seed {
612     my $c = shift;
613
614     return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
615 }
616
617 my $usable;
618
619 sub _find_digest () {
620     unless ($usable) {
621         foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
622             if ( eval { Digest->new($alg) } ) {
623                 $usable = $alg;
624                 last;
625             }
626         }
627         Catalyst::Exception->throw(
628                 "Could not find a suitable Digest module. Please install "
629               . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
630           unless $usable;
631     }
632
633     return Digest->new($usable);
634 }
635
636 sub dump_these {
637     my $c = shift;
638
639     (
640         $c->maybe::next::method(),
641
642         $c->_sessionid
643         ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
644         : ()
645     );
646 }
647
648
649 sub get_session_id { shift->maybe::next::method(@_) }
650 sub set_session_id { shift->maybe::next::method(@_) }
651 sub delete_session_id { shift->maybe::next::method(@_) }
652 sub extend_session_id { shift->maybe::next::method(@_) }
653
654 __PACKAGE__;
655
656 __END__
657
658 =pod
659
660 =head1 NAME
661
662 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
663
664 =head1 SYNOPSIS
665
666     # To get sessions to "just work", all you need to do is use these plugins:
667
668     use Catalyst qw/
669       Session
670       Session::Store::FastMmap
671       Session::State::Cookie
672       /;
673
674     # you can replace Store::FastMmap with Store::File - both have sensible
675     # default configurations (see their docs for details)
676
677     # more complicated backends are available for other scenarios (DBI storage,
678     # etc)
679
680
681     # after you've loaded the plugins you can save session data
682     # For example, if you are writing a shopping cart, it could be implemented
683     # like this:
684
685     sub add_item : Local {
686         my ( $self, $c ) = @_;
687
688         my $item_id = $c->req->param("item");
689
690         # $c->session is a hash ref, a bit like $c->stash
691         # the difference is that it' preserved across requests
692
693         push @{ $c->session->{items} }, $item_id;
694
695         $c->forward("MyView");
696     }
697
698     sub display_items : Local {
699         my ( $self, $c ) = @_;
700
701         # values in $c->session are restored
702         $c->stash->{items_to_display} =
703           [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
704
705         $c->forward("MyView");
706     }
707
708 =head1 DESCRIPTION
709
710 The Session plugin is the base of two related parts of functionality required
711 for session management in web applications.
712
713 The first part, the State, is getting the browser to repeat back a session key,
714 so that the web application can identify the client and logically string
715 several requests together into a session.
716
717 The second part, the Store, deals with the actual storage of information about
718 the client. This data is stored so that the it may be revived for every request
719 made by the same client.
720
721 This plugin links the two pieces together.
722
723 =head1 RECOMENDED BACKENDS
724
725 =over 4
726
727 =item Session::State::Cookie
728
729 The only really sane way to do state is using cookies.
730
731 =item Session::Store::File
732
733 A portable backend, based on Cache::File.
734
735 =item Session::Store::FastMmap
736
737 A fast and flexible backend, based on Cache::FastMmap.
738
739 =back
740
741 =head1 METHODS
742
743 =over 4
744
745 =item sessionid
746
747 An accessor for the session ID value.
748
749 =item session
750
751 Returns a hash reference that might contain unserialized values from previous
752 requests in the same session, and whose modified value will be saved for future
753 requests.
754
755 This method will automatically create a new session and session ID if none
756 exists.
757
758 You can also set session keys by passing a list of key/value pairs or a
759 hashref.
760
761     $c->session->{foo} = "bar";      # This works.
762     $c->session(one => 1, two => 2); # And this.
763     $c->session({ answer => 42 });   # And this.
764
765 =item session_expires
766
767 This method returns the time when the current session will expire, or 0 if
768 there is no current session. If there is a session and it already expired, it
769 will delete the session and return 0 as well.
770
771 =item flash
772
773 This is like Ruby on Rails' flash data structure. Think of it as a stash that
774 lasts for longer than one request, letting you redirect instead of forward.
775
776 The flash data will be cleaned up only on requests on which actually use
777 $c->flash (thus allowing multiple redirections), and the policy is to delete
778 all the keys which haven't changed since the flash data was loaded at the end
779 of every request.
780
781 Note that use of the flash is an easy way to get data across requests, but
782 it's also strongly disrecommended, due it it being inherently plagued with
783 race conditions. This means that it's unlikely to work well if your
784 users have multiple tabs open at once, or if your site does a lot of AJAX
785 requests.
786
787 L<Catalyst::Plugin::StatusMessage> is the recommended alternative solution,
788 as this doesn't suffer from these issues.
789
790     sub moose : Local {
791         my ( $self, $c ) = @_;
792
793         $c->flash->{beans} = 10;
794         $c->response->redirect( $c->uri_for("foo") );
795     }
796
797     sub foo : Local {
798         my ( $self, $c ) = @_;
799
800         my $value = $c->flash->{beans};
801
802         # ...
803
804         $c->response->redirect( $c->uri_for("bar") );
805     }
806
807     sub bar : Local {
808         my ( $self, $c ) = @_;
809
810         if ( exists $c->flash->{beans} ) { # false
811
812         }
813     }
814
815 =item clear_flash
816
817 Zap all the keys in the flash regardless of their current state.
818
819 =item keep_flash @keys
820
821 If you want to keep a flash key for the next request too, even if it hasn't
822 changed, call C<keep_flash> and pass in the keys as arguments.
823
824 =item delete_session REASON
825
826 This method is used to invalidate a session. It takes an optional parameter
827 which will be saved in C<session_delete_reason> if provided.
828
829 NOTE: This method will B<also> delete your flash data.
830
831 =item session_delete_reason
832
833 This accessor contains a string with the reason a session was deleted. Possible
834 values include:
835
836 =over 4
837
838 =item *
839
840 C<address mismatch>
841
842 =item *
843
844 C<session expired>
845
846 =back
847
848 =item session_expire_key $key, $ttl
849
850 Mark a key to expire at a certain time (only useful when shorter than the
851 expiry time for the whole session).
852
853 For example:
854
855     __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # "forever"
856     (NB If this number is too large, Y2K38 breakage could result.)
857
858     # later
859
860     $c->session_expire_key( __user => 3600 );
861
862 Will make the session data survive, but the user will still be logged out after
863 an hour.
864
865 Note that these values are not auto extended.
866
867 =item change_session_id
868
869 By calling this method you can force a session id change while keeping all
870 session data. This method might come handy when you are paranoid about some
871 advanced variations of session fixation attack.
872
873 If you want to prevent this session fixation scenario:
874
875     0) let us have WebApp with anonymous and authenticated parts
876     1) a hacker goes to vulnerable WebApp and gets a real sessionid,
877        just by browsing anonymous part of WebApp
878     2) the hacker inserts (somehow) this values into a cookie in victim's browser
879     3) after the victim logs into WebApp the hacker can enter his/her session
880
881 you should call change_session_id in your login controller like this:
882
883       if ($c->authenticate( { username => $user, password => $pass } )) {
884         # login OK
885         $c->change_session_id;
886         ...
887       } else {
888         # login FAILED
889         ...
890       }
891
892 =item change_session_expires $expires
893
894 You can change the session expiration time for this session;
895
896     $c->change_session_expires( 4000 );
897
898 Note that this only works to set the session longer than the config setting.
899
900 =back
901
902 =head1 INTERNAL METHODS
903
904 =over 4
905
906 =item setup
907
908 This method is extended to also make calls to
909 C<check_session_plugin_requirements> and C<setup_session>.
910
911 =item check_session_plugin_requirements
912
913 This method ensures that a State and a Store plugin are also in use by the
914 application.
915
916 =item setup_session
917
918 This method populates C<< $c->config('Plugin::Session') >> with the default values
919 listed in L</CONFIGURATION>.
920
921 =item prepare_action
922
923 This method is extended.
924
925 Its only effect is if the (off by default) C<flash_to_stash> configuration
926 parameter is on - then it will copy the contents of the flash to the stash at
927 prepare time.
928
929 =item finalize_headers
930
931 This method is extended and will extend the expiry time before sending
932 the response.
933
934 =item finalize_body
935
936 This method is extended and will call finalize_session before the other
937 finalize_body methods run.  Here we persist the session data if a session exists.
938
939 =item initialize_session_data
940
941 This method will initialize the internal structure of the session, and is
942 called by the C<session> method if appropriate.
943
944 =item create_session_id
945
946 Creates a new session ID using C<generate_session_id> if there is no session ID
947 yet.
948
949 =item validate_session_id SID
950
951 Make sure a session ID is of the right format.
952
953 This currently ensures that the session ID string is any amount of case
954 insensitive hexadecimal characters.
955
956 =item generate_session_id
957
958 This method will return a string that can be used as a session ID. It is
959 supposed to be a reasonably random string with enough bits to prevent
960 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
961 MD5 or SHA-256, depending on the availability of these modules.
962
963 =item session_hash_seed
964
965 This method is actually rather internal to generate_session_id, but should be
966 overridable in case you want to provide more random data.
967
968 Currently it returns a concatenated string which contains:
969
970 =over 4
971
972 =item * A counter
973
974 =item * The current time
975
976 =item * One value from C<rand>.
977
978 =item * The stringified value of a newly allocated hash reference
979
980 =item * The stringified value of the Catalyst context object
981
982 =back
983
984 in the hopes that those combined values are entropic enough for most uses. If
985 this is not the case you can replace C<session_hash_seed> with e.g.
986
987     sub session_hash_seed {
988         open my $fh, "<", "/dev/random";
989         read $fh, my $bytes, 20;
990         close $fh;
991         return $bytes;
992     }
993
994 Or even more directly, replace C<generate_session_id>:
995
996     sub generate_session_id {
997         open my $fh, "<", "/dev/random";
998         read $fh, my $bytes, 20;
999         close $fh;
1000         return unpack("H*", $bytes);
1001     }
1002
1003 Also have a look at L<Crypt::Random> and the various openssl bindings - these
1004 modules provide APIs for cryptographically secure random data.
1005
1006 =item finalize_session
1007
1008 Clean up the session during C<finalize>.
1009
1010 This clears the various accessors after saving to the store.
1011
1012 =item dump_these
1013
1014 See L<Catalyst/dump_these> - ammends the session data structure to the list of
1015 dumped objects if session ID is defined.
1016
1017
1018 =item calculate_extended_session_expires
1019
1020 =item calculate_initial_session_expires
1021
1022 =item create_session_id_if_needed
1023
1024 =item delete_session_id
1025
1026 =item extend_session_expires
1027
1028 Note: this is *not* used to give an individual user a longer session. See
1029 'change_session_expires'.
1030
1031 =item extend_session_id
1032
1033 =item get_session_id
1034
1035 =item reset_session_expires
1036
1037 =item session_is_valid
1038
1039 =item set_session_id
1040
1041 =item initial_session_expires
1042
1043 =back
1044
1045 =head1 USING SESSIONS DURING PREPARE
1046
1047 The earliest point in time at which you may use the session data is after
1048 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
1049
1050 State plugins must set $c->session ID before C<prepare_action>, and during
1051 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
1052 the store.
1053
1054     sub prepare_action {
1055         my $c = shift;
1056
1057         # don't touch $c->session yet!
1058
1059         $c->NEXT::prepare_action( @_ );
1060
1061         $c->session;  # this is OK
1062         $c->sessionid; # this is also OK
1063     }
1064
1065 =head1 CONFIGURATION
1066
1067     $c->config('Plugin::Session' => {
1068         expires => 1234,
1069     });
1070
1071 All configuation parameters are provided in a hash reference under the
1072 C<Plugin::Session> key in the configuration hash.
1073
1074 =over 4
1075
1076 =item expires
1077
1078 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
1079 hours).
1080
1081 =item expiry_threshold
1082
1083 Only update the session expiry time if it would otherwise expire
1084 within this many seconds from now.
1085
1086 The purpose of this is to keep the session store from being updated
1087 when nothing else in the session is updated.
1088
1089 Defaults to 0 (in which case, the expiration will always be updated).
1090
1091 =item verify_address
1092
1093 When true, C<< $c->request->address >> will be checked at prepare time. If it is
1094 not the same as the address that initiated the session, the session is deleted.
1095
1096 Defaults to false.
1097
1098 =item verify_user_agent
1099
1100 When true, C<< $c->request->user_agent >> will be checked at prepare time. If it
1101 is not the same as the user agent that initiated the session, the session is
1102 deleted.
1103
1104 Defaults to false.
1105
1106 =item flash_to_stash
1107
1108 This option makes it easier to have actions behave the same whether they were
1109 forwarded to or redirected to. On prepare time it copies the contents of
1110 C<flash> (if any) to the stash.
1111
1112 =back
1113
1114 =head1 SPECIAL KEYS
1115
1116 The hash reference returned by C<< $c->session >> contains several keys which
1117 are automatically set:
1118
1119 =over 4
1120
1121 =item __expires
1122
1123 This key no longer exists. Use C<session_expires> instead.
1124
1125 =item __updated
1126
1127 The last time a session was saved to the store.
1128
1129 =item __created
1130
1131 The time when the session was first created.
1132
1133 =item __address
1134
1135 The value of C<< $c->request->address >> at the time the session was created.
1136 This value is only populated if C<verify_address> is true in the configuration.
1137
1138 =item __user_agent
1139
1140 The value of C<< $c->request->user_agent >> at the time the session was created.
1141 This value is only populated if C<verify_user_agent> is true in the configuration.
1142
1143 =back
1144
1145 =head1 CAVEATS
1146
1147 =head2 Round the Robin Proxies
1148
1149 C<verify_address> could make your site inaccessible to users who are behind
1150 load balanced proxies. Some ISPs may give a different IP to each request by the
1151 same client due to this type of proxying. If addresses are verified these
1152 users' sessions cannot persist.
1153
1154 To let these users access your site you can either disable address verification
1155 as a whole, or provide a checkbox in the login dialog that tells the server
1156 that it's OK for the address of the client to change. When the server sees that
1157 this box is checked it should delete the C<__address> special key from the
1158 session hash when the hash is first created.
1159
1160 =head2 Race Conditions
1161
1162 In this day and age where cleaning detergents and Dutch football (not the
1163 American kind) teams roam the plains in great numbers, requests may happen
1164 simultaneously. This means that there is some risk of session data being
1165 overwritten, like this:
1166
1167 =over 4
1168
1169 =item 1.
1170
1171 request a starts, request b starts, with the same session ID
1172
1173 =item 2.
1174
1175 session data is loaded in request a
1176
1177 =item 3.
1178
1179 session data is loaded in request b
1180
1181 =item 4.
1182
1183 session data is changed in request a
1184
1185 =item 5.
1186
1187 request a finishes, session data is updated and written to store
1188
1189 =item 6.
1190
1191 request b finishes, session data is updated and written to store, overwriting
1192 changes by request a
1193
1194 =back
1195
1196 For applications where any given user's session is only making one request
1197 at a time this plugin should be safe enough.
1198
1199 =head1 AUTHORS
1200
1201 Andy Grundman
1202
1203 Christian Hansen
1204
1205 Yuval Kogman, C<nothingmuch@woobling.org>
1206
1207 Sebastian Riedel
1208
1209 Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)
1210
1211 Sergio Salvi
1212
1213 kmx C<kmx@volny.cz>
1214
1215 Florian Ragwitz (rafl) C<rafl@debian.org>
1216
1217 Kent Fredric (kentnl)
1218
1219 And countless other contributers from #catalyst. Thanks guys!
1220
1221 =head1 Contributors
1222
1223 Devin Austin (dhoss) <dhoss@cpan.org>
1224
1225 Robert Rothenberg <rrwo@cpan.org>
1226
1227 =head1 COPYRIGHT & LICENSE
1228
1229     Copyright (c) 2005 the aforementioned authors. All rights
1230     reserved. This program is free software; you can redistribute
1231     it and/or modify it under the same terms as Perl itself.
1232
1233 =cut
1234
1235