3 package Catalyst::Plugin::Session;
4 use base qw/Class::Accessor::Fast/;
10 use Catalyst::Exception ();
13 use Object::Signature ();
16 our $VERSION = '0.20';
18 my @session_data_accessors; # used in delete_session
20 __PACKAGE__->mk_accessors(
21 "_session_delete_reason",
22 @session_data_accessors = qw/
26 _extended_session_expires
31 _tried_loading_session_id
32 _tried_loading_session_data
33 _tried_loading_session_expires
34 _tried_loading_flash_data
44 $c->check_session_plugin_requirements;
50 sub check_session_plugin_requirements {
53 unless ( $c->isa("Catalyst::Plugin::Session::State")
54 && $c->isa("Catalyst::Plugin::Session::Store") )
57 ( "The Session plugin requires both Session::State "
58 . "and Session::Store plugins to be used as well." );
61 Catalyst::Exception->throw($err);
68 my $cfg = ( $c->config->{session} ||= {} );
76 $c->NEXT::setup_session();
82 if ( $c->config->{session}{flash_to_stash}
84 and my $flash_data = $c->flash )
86 @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
89 $c->NEXT::prepare_action(@_);
92 sub finalize_headers {
95 # fix cookie before we send headers
96 $c->_save_session_expires;
98 return $c->NEXT::finalize_headers(@_);
103 my $ret = $c->NEXT::finalize(@_);
105 # then finish the rest
106 $c->finalize_session;
110 sub finalize_session {
113 $c->NEXT::finalize_session;
115 $c->_save_session_id;
119 $c->_clear_session_instance_data;
122 sub _save_session_id {
125 # we already called set when allocating
126 # no need to tell the state plugins anything new
129 sub _save_session_expires {
132 if ( defined($c->_session_expires) ) {
133 my $expires = $c->session_expires; # force extension
135 my $sid = $c->sessionid;
136 $c->store_session_data( "expires:$sid" => $expires );
143 if ( my $session_data = $c->_session ) {
145 no warnings 'uninitialized';
146 if ( Object::Signature::signature($session_data) ne
147 $c->_session_data_sig )
149 $session_data->{__updated} = time();
150 my $sid = $c->sessionid;
151 $c->store_session_data( "session:$sid" => $session_data );
159 if ( my $flash_data = $c->_flash ) {
161 my $hashes = $c->_flash_key_hashes || {};
162 my $keep = $c->_flash_keep_keys || {};
163 foreach my $key ( keys %$hashes ) {
164 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
165 delete $flash_data->{$key};
169 my $sid = $c->sessionid;
172 $c->store_session_data( "flash:$sid", $flash_data );
175 $c->delete_session_data("flash:$sid");
180 sub _load_session_expires {
182 return $c->_session_expires if $c->_tried_loading_session_expires;
183 $c->_tried_loading_session_expires(1);
185 if ( my $sid = $c->sessionid ) {
186 my $expires = $c->get_session_data("expires:$sid") || 0;
188 if ( $expires >= time() ) {
189 $c->_session_expires( $expires );
192 $c->delete_session( "session expired" );
202 return $c->_session if $c->_tried_loading_session_data;
203 $c->_tried_loading_session_data(1);
205 if ( my $sid = $c->sessionid ) {
206 if ( $c->_load_session_expires ) { # > 0
208 my $session_data = $c->get_session_data("session:$sid") || return;
209 $c->_session($session_data);
211 no warnings 'uninitialized'; # ne __address
212 if ( $c->config->{session}{verify_address}
213 && $session_data->{__address} ne $c->request->address )
216 "Deleting session $sid due to address mismatch ("
217 . $session_data->{__address} . " != "
218 . $c->request->address . ")"
220 $c->delete_session("address mismatch");
224 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
225 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
226 $c->_expire_session_keys;
228 return $session_data;
237 return $c->_flash if $c->_tried_loading_flash_data;
238 $c->_tried_loading_flash_data(1);
240 if ( my $sid = $c->sessionid ) {
241 if ( my $flash_data = $c->_flash
242 || $c->_flash( $c->get_session_data("flash:$sid") ) )
244 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
253 sub _expire_session_keys {
254 my ( $c, $data ) = @_;
258 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
259 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
260 delete $c->_session->{$key};
261 delete $expire_times->{$key};
265 sub _clear_session_instance_data {
267 $c->$_(undef) for @session_data_accessors;
268 $c->NEXT::_clear_session_instance_data; # allow other plugins to hook in on this
272 my ( $c, $msg ) = @_;
274 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
276 # delete the session data
277 if ( my $sid = $c->sessionid ) {
278 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
279 $c->delete_session_id($sid);
282 # reset the values in the context object
283 # see the BEGIN block
284 $c->_clear_session_instance_data;
286 $c->_session_delete_reason($msg);
289 sub session_delete_reason {
292 $c->session_is_valid; # check that it was loaded
294 $c->_session_delete_reason(@_);
297 sub session_expires {
300 if ( defined( my $expires = $c->_extended_session_expires ) ) {
302 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
303 return $c->extend_session_expires( $expires );
309 sub extend_session_expires {
310 my ( $c, $expires ) = @_;
311 $c->_extended_session_expires( my $updated = $c->calculate_extended_session_expires( $expires ) );
312 $c->extend_session_id( $c->sessionid, $updated );
316 sub calculate_initial_session_expires {
318 return ( time() + $c->config->{session}{expires} );
321 sub calculate_extended_session_expires {
322 my ( $c, $prev ) = @_;
323 $c->calculate_initial_session_expires;
326 sub reset_session_expires {
327 my ( $c, $sid ) = @_;
329 my $exp = $c->calculate_initial_session_expires;
330 $c->_session_expires( $exp );
331 $c->_extended_session_expires( $exp );
338 return $c->_sessionid || $c->_load_sessionid;
341 sub _load_sessionid {
343 return if $c->_tried_loading_session_id;
344 $c->_tried_loading_session_id(1);
346 if ( defined( my $sid = $c->get_session_id ) ) {
347 if ( $c->validate_session_id($sid) ) {
348 # temporarily set the inner key, so that validation will work
349 $c->_sessionid($sid);
352 my $err = "Tried to set invalid session ID '$sid'";
353 $c->log->error($err);
354 Catalyst::Exception->throw($err);
361 sub session_is_valid {
364 # force a check for expiry, but also __address, etc
365 if ( $c->_load_session ) {
372 sub validate_session_id {
373 my ( $c, $sid ) = @_;
375 $sid and $sid =~ /^[a-f\d]+$/i;
381 $c->_session || $c->_load_session || do {
382 $c->create_session_id_if_needed;
383 $c->initialize_session_data;
388 my ( $c, @keys ) = @_;
389 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
390 (@{$href}{@keys}) = ((undef) x @keys);
395 $c->_flash || $c->_load_flash || do {
396 $c->create_session_id_if_needed;
404 my $items = @_ > 1 ? {@_} : $_[0];
405 croak('flash takes a hash or hashref') unless ref $items;
406 @{ $c->_flash }{ keys %$items } = values %$items;
420 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
421 $c->_flash_key_hashes({});
422 $c->_flash_keep_keys({});
426 sub session_expire_key {
427 my ( $c, %keys ) = @_;
430 @{ $c->session->{__expire_keys} }{ keys %keys } =
431 map { $now + $_ } values %keys;
434 sub initialize_session_data {
445 $c->config->{session}{verify_address}
446 ? ( __address => $c->request->address )
453 sub generate_session_id {
456 my $digest = $c->_find_digest();
457 $digest->add( $c->session_hash_seed() );
458 return $digest->hexdigest;
461 sub create_session_id_if_needed {
463 $c->create_session_id unless $c->sessionid;
466 sub create_session_id {
469 my $sid = $c->generate_session_id;
471 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
473 $c->_sessionid($sid);
474 $c->reset_session_expires;
475 $c->set_session_id($sid);
482 sub session_hash_seed {
485 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
490 sub _find_digest () {
492 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
493 if ( eval { Digest->new($alg) } ) {
498 Catalyst::Exception->throw(
499 "Could not find a suitable Digest module. Please install "
500 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
504 return Digest->new($usable);
511 $c->NEXT::dump_these(),
514 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
520 sub get_session_id { shift->NEXT::get_session_id(@_) }
521 sub set_session_id { shift->NEXT::set_session_id(@_) }
522 sub delete_session_id { shift->NEXT::delete_session_id(@_) }
523 sub extend_session_id { shift->NEXT::extend_session_id(@_) }
533 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
537 # To get sessions to "just work", all you need to do is use these plugins:
541 Session::Store::FastMmap
542 Session::State::Cookie
545 # you can replace Store::FastMmap with Store::File - both have sensible
546 # default configurations (see their docs for details)
548 # more complicated backends are available for other scenarios (DBI storage,
552 # after you've loaded the plugins you can save session data
553 # For example, if you are writing a shopping cart, it could be implemented
556 sub add_item : Local {
557 my ( $self, $c ) = @_;
559 my $item_id = $c->req->param("item");
561 # $c->session is a hash ref, a bit like $c->stash
562 # the difference is that it' preserved across requests
564 push @{ $c->session->{items} }, $item_id;
566 $c->forward("MyView");
569 sub display_items : Local {
570 my ( $self, $c ) = @_;
572 # values in $c->session are restored
573 $c->stash->{items_to_display} =
574 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
576 $c->forward("MyView");
581 The Session plugin is the base of two related parts of functionality required
582 for session management in web applications.
584 The first part, the State, is getting the browser to repeat back a session key,
585 so that the web application can identify the client and logically string
586 several requests together into a session.
588 The second part, the Store, deals with the actual storage of information about
589 the client. This data is stored so that the it may be revived for every request
590 made by the same client.
592 This plugin links the two pieces together.
594 =head1 RECOMENDED BACKENDS
598 =item Session::State::Cookie
600 The only really sane way to do state is using cookies.
602 =item Session::Store::File
604 A portable backend, based on Cache::File.
606 =item Session::Store::FastMmap
608 A fast and flexible backend, based on Cache::FastMmap.
618 An accessor for the session ID value.
622 Returns a hash reference that might contain unserialized values from previous
623 requests in the same session, and whose modified value will be saved for future
626 This method will automatically create a new session and session ID if none
629 =item session_expires
631 =item session_expires $reset
633 This method returns the time when the current session will expire, or 0 if
634 there is no current session. If there is a session and it already expired, it
635 will delete the session and return 0 as well.
637 If the C<$reset> parameter is true, and there is a session ID the expiry time
638 will be reset to the current time plus the time to live (see
639 L</CONFIGURATION>). This is used when creating a new session.
643 This is like Ruby on Rails' flash data structure. Think of it as a stash that
644 lasts for longer than one request, letting you redirect instead of forward.
646 The flash data will be cleaned up only on requests on which actually use
647 $c->flash (thus allowing multiple redirections), and the policy is to delete
648 all the keys which haven't changed since the flash data was loaded at the end
652 my ( $self, $c ) = @_;
654 $c->flash->{beans} = 10;
655 $c->response->redirect( $c->uri_for("foo") );
659 my ( $self, $c ) = @_;
661 my $value = $c->flash->{beans};
665 $c->response->redirect( $c->uri_for("bar") );
669 my ( $self, $c ) = @_;
671 if ( exists $c->flash->{beans} ) { # false
678 Zap all the keys in the flash regardless of their current state.
680 =item keep_flash @keys
682 If you want to keep a flash key for the next request too, even if it hasn't
683 changed, call C<keep_flash> and pass in the keys as arguments.
685 =item delete_session REASON
687 This method is used to invalidate a session. It takes an optional parameter
688 which will be saved in C<session_delete_reason> if provided.
690 =item session_delete_reason
692 This accessor contains a string with the reason a session was deleted. Possible
707 =item session_expire_key $key, $ttl
709 Mark a key to expire at a certain time (only useful when shorter than the
710 expiry time for the whole session).
714 __PACKAGE__->config->{session}{expires} = 1000000000000; # forever
718 $c->session_expire_key( __user => 3600 );
720 Will make the session data survive, but the user will still be logged out after
723 Note that these values are not auto extended.
727 =head1 INTERNAL METHODS
733 This method is extended to also make calls to
734 C<check_session_plugin_requirements> and C<setup_session>.
736 =item check_session_plugin_requirements
738 This method ensures that a State and a Store plugin are also in use by the
743 This method populates C<< $c->config->{session} >> with the default values
744 listed in L</CONFIGURATION>.
748 This methoid is extended.
750 It's only effect is if the (off by default) C<flash_to_stash> configuration
751 parameter is on - then it will copy the contents of the flash to the stash at
754 =item finalize_headers
756 This method is extended and will extend the expiry time before sending
761 This method is extended and will call finalize_session after the other
762 finalizes run. Here we persist the session data if a session exists.
764 =item initialize_session_data
766 This method will initialize the internal structure of the session, and is
767 called by the C<session> method if appropriate.
769 =item create_session_id
771 Creates a new session id using C<generate_session_id> if there is no session ID
774 =item validate_session_id SID
776 Make sure a session ID is of the right format.
778 This currently ensures that the session ID string is any amount of case
779 insensitive hexadecimal characters.
781 =item generate_session_id
783 This method will return a string that can be used as a session ID. It is
784 supposed to be a reasonably random string with enough bits to prevent
785 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
786 MD5 or SHA-256, depending on the availibility of these modules.
788 =item session_hash_seed
790 This method is actually rather internal to generate_session_id, but should be
791 overridable in case you want to provide more random data.
793 Currently it returns a concatenated string which contains:
799 =item * The current time
801 =item * One value from C<rand>.
803 =item * The stringified value of a newly allocated hash reference
805 =item * The stringified value of the Catalyst context object
809 In the hopes that those combined values are entropic enough for most uses. If
810 this is not the case you can replace C<session_hash_seed> with e.g.
812 sub session_hash_seed {
813 open my $fh, "<", "/dev/random";
814 read $fh, my $bytes, 20;
819 Or even more directly, replace C<generate_session_id>:
821 sub generate_session_id {
822 open my $fh, "<", "/dev/random";
823 read $fh, my $bytes, 20;
825 return unpack("H*", $bytes);
828 Also have a look at L<Crypt::Random> and the various openssl bindings - these
829 modules provide APIs for cryptographically secure random data.
831 =item finalize_session
833 Clean up the session during C<finalize>.
835 This clears the various accessors after saving to the store.
839 See L<Catalyst/dump_these> - ammends the session data structure to the list of
840 dumped objects if session ID is defined.
843 =item calculate_extended_session_expires
845 =item calculate_initial_session_expires
847 =item create_session_id_if_needed
849 =item delete_session_id
851 =item extend_session_expires
853 =item extend_session_id
857 =item reset_session_expires
859 =item session_is_valid
865 =head1 USING SESSIONS DURING PREPARE
867 The earliest point in time at which you may use the session data is after
868 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
870 State plugins must set $c->session ID before C<prepare_action>, and during
871 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
877 # don't touch $c->session yet!
879 $c->NEXT::prepare_action( @_ );
881 $c->session; # this is OK
882 $c->sessionid; # this is also OK
887 $c->config->{session} = {
891 All configuation parameters are provided in a hash reference under the
892 C<session> key in the configuration hash.
898 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
903 When true, C<<$c->request->address>> will be checked at prepare time. If it is
904 not the same as the address that initiated the session, the session is deleted.
910 This option makes it easier to have actions behave the same whether they were
911 forwarded to or redirected to. On prepare time it copies the contents of
912 C<flash> (if any) to the stash.
918 The hash reference returned by C<< $c->session >> contains several keys which
919 are automatically set:
925 This key no longer exists. Use C<session_expires> instead.
929 The last time a session was saved to the store.
933 The time when the session was first created.
937 The value of C<< $c->request->address >> at the time the session was created.
938 This value is only populated if C<verify_address> is true in the configuration.
944 =head2 Round the Robin Proxies
946 C<verify_address> could make your site inaccessible to users who are behind
947 load balanced proxies. Some ISPs may give a different IP to each request by the
948 same client due to this type of proxying. If addresses are verified these
949 users' sessions cannot persist.
951 To let these users access your site you can either disable address verification
952 as a whole, or provide a checkbox in the login dialog that tells the server
953 that it's OK for the address of the client to change. When the server sees that
954 this box is checked it should delete the C<__address> sepcial key from the
955 session hash when the hash is first created.
957 =head2 Race Conditions
959 In this day and age where cleaning detergents and dutch football (not the
960 american kind) teams roam the plains in great numbers, requests may happen
961 simultaneously. This means that there is some risk of session data being
962 overwritten, like this:
968 request a starts, request b starts, with the same session id
972 session data is loaded in request a
976 session data is loaded in request b
980 session data is changed in request a
984 request a finishes, session data is updated and written to store
988 request b finishes, session data is updated and written to store, overwriting
993 If this is a concern in your application, a soon to be developed locking
994 solution is the only safe way to go. This will have a bigger overhead.
996 For applications where any given user is only making one request at a time this
997 plugin should be safe enough.
1005 Yuval Kogman, C<nothingmuch@woobling.org> (current maintainer)
1009 And countless other contributers from #catalyst. Thanks guys!
1011 =head1 COPYRIGHT & LICENSE
1013 Copyright (c) 2005 the aforementioned authors. All rights
1014 reserved. This program is free software; you can redistribute
1015 it and/or modify it under the same terms as Perl itself.