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