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