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