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