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(@_);
104 # We have to finalize our session *before* $c->engine->finalize_xxx is called,
105 # because we do not want to send the HTTP response before the session is stored/committed to
106 # the session database (or whatever Session::Store you use).
107 $c->finalize_session;
109 return $c->NEXT::finalize_body(@_);
112 sub finalize_session {
115 $c->NEXT::finalize_session;
117 $c->_save_session_id;
121 $c->_clear_session_instance_data;
124 sub _save_session_id {
127 # we already called set when allocating
128 # no need to tell the state plugins anything new
131 sub _save_session_expires {
134 if ( defined($c->_session_expires) ) {
135 my $expires = $c->session_expires; # force extension
137 my $sid = $c->sessionid;
138 $c->store_session_data( "expires:$sid" => $expires );
145 if ( my $session_data = $c->_session ) {
147 no warnings 'uninitialized';
148 if ( Object::Signature::signature($session_data) ne
149 $c->_session_data_sig )
151 $session_data->{__updated} = time();
152 my $sid = $c->sessionid;
153 $c->store_session_data( "session:$sid" => $session_data );
161 if ( my $flash_data = $c->_flash ) {
163 my $hashes = $c->_flash_key_hashes || {};
164 my $keep = $c->_flash_keep_keys || {};
165 foreach my $key ( keys %$hashes ) {
166 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
167 delete $flash_data->{$key};
171 my $sid = $c->sessionid;
174 $c->store_session_data( "flash:$sid", $flash_data );
177 $c->delete_session_data("flash:$sid");
182 sub _load_session_expires {
184 return $c->_session_expires if $c->_tried_loading_session_expires;
185 $c->_tried_loading_session_expires(1);
187 if ( my $sid = $c->sessionid ) {
188 my $expires = $c->get_session_data("expires:$sid") || 0;
190 if ( $expires >= time() ) {
191 $c->_session_expires( $expires );
194 $c->delete_session( "session expired" );
204 return $c->_session if $c->_tried_loading_session_data;
205 $c->_tried_loading_session_data(1);
207 if ( my $sid = $c->sessionid ) {
208 if ( $c->_load_session_expires ) { # > 0
210 my $session_data = $c->get_session_data("session:$sid") || return;
211 $c->_session($session_data);
213 no warnings 'uninitialized'; # ne __address
214 if ( $c->config->{session}{verify_address}
215 && $session_data->{__address} ne $c->request->address )
218 "Deleting session $sid due to address mismatch ("
219 . $session_data->{__address} . " != "
220 . $c->request->address . ")"
222 $c->delete_session("address mismatch");
226 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
227 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
228 $c->_expire_session_keys;
230 return $session_data;
239 return $c->_flash if $c->_tried_loading_flash_data;
240 $c->_tried_loading_flash_data(1);
242 if ( my $sid = $c->sessionid ) {
243 if ( my $flash_data = $c->_flash
244 || $c->_flash( $c->get_session_data("flash:$sid") ) )
246 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
255 sub _expire_session_keys {
256 my ( $c, $data ) = @_;
260 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
261 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
262 delete $c->_session->{$key};
263 delete $expire_times->{$key};
267 sub _clear_session_instance_data {
269 $c->$_(undef) for @session_data_accessors;
270 $c->NEXT::_clear_session_instance_data; # allow other plugins to hook in on this
274 my ( $c, $msg ) = @_;
276 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
278 # delete the session data
279 if ( my $sid = $c->sessionid ) {
280 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
281 $c->delete_session_id($sid);
284 # reset the values in the context object
285 # see the BEGIN block
286 $c->_clear_session_instance_data;
288 $c->_session_delete_reason($msg);
291 sub session_delete_reason {
294 $c->session_is_valid; # check that it was loaded
296 $c->_session_delete_reason(@_);
299 sub session_expires {
302 if ( defined( my $expires = $c->_extended_session_expires ) ) {
304 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
305 return $c->extend_session_expires( $expires );
311 sub extend_session_expires {
312 my ( $c, $expires ) = @_;
313 $c->_extended_session_expires( my $updated = $c->calculate_extended_session_expires( $expires ) );
314 $c->extend_session_id( $c->sessionid, $updated );
318 sub calculate_initial_session_expires {
320 return ( time() + $c->config->{session}{expires} );
323 sub calculate_extended_session_expires {
324 my ( $c, $prev ) = @_;
325 $c->calculate_initial_session_expires;
328 sub reset_session_expires {
329 my ( $c, $sid ) = @_;
331 my $exp = $c->calculate_initial_session_expires;
332 $c->_session_expires( $exp );
333 $c->_extended_session_expires( $exp );
340 return $c->_sessionid || $c->_load_sessionid;
343 sub _load_sessionid {
345 return if $c->_tried_loading_session_id;
346 $c->_tried_loading_session_id(1);
348 if ( defined( my $sid = $c->get_session_id ) ) {
349 if ( $c->validate_session_id($sid) ) {
350 # temporarily set the inner key, so that validation will work
351 $c->_sessionid($sid);
354 my $err = "Tried to set invalid session ID '$sid'";
355 $c->log->error($err);
356 Catalyst::Exception->throw($err);
363 sub session_is_valid {
366 # force a check for expiry, but also __address, etc
367 if ( $c->_load_session ) {
374 sub validate_session_id {
375 my ( $c, $sid ) = @_;
377 $sid and $sid =~ /^[a-f\d]+$/i;
383 $c->_session || $c->_load_session || do {
384 $c->create_session_id_if_needed;
385 $c->initialize_session_data;
390 my ( $c, @keys ) = @_;
391 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
392 (@{$href}{@keys}) = ((undef) x @keys);
397 $c->_flash || $c->_load_flash || do {
398 $c->create_session_id_if_needed;
406 my $items = @_ > 1 ? {@_} : $_[0];
407 croak('flash takes a hash or hashref') unless ref $items;
408 @{ $c->_flash }{ keys %$items } = values %$items;
422 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
423 $c->_flash_key_hashes({});
424 $c->_flash_keep_keys({});
428 sub session_expire_key {
429 my ( $c, %keys ) = @_;
432 @{ $c->session->{__expire_keys} }{ keys %keys } =
433 map { $now + $_ } values %keys;
436 sub initialize_session_data {
447 $c->config->{session}{verify_address}
448 ? ( __address => $c->request->address )
455 sub generate_session_id {
458 my $digest = $c->_find_digest();
459 $digest->add( $c->session_hash_seed() );
460 return $digest->hexdigest;
463 sub create_session_id_if_needed {
465 $c->create_session_id unless $c->sessionid;
468 sub create_session_id {
471 my $sid = $c->generate_session_id;
473 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
475 $c->_sessionid($sid);
476 $c->reset_session_expires;
477 $c->set_session_id($sid);
484 sub session_hash_seed {
487 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
492 sub _find_digest () {
494 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
495 if ( eval { Digest->new($alg) } ) {
500 Catalyst::Exception->throw(
501 "Could not find a suitable Digest module. Please install "
502 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
506 return Digest->new($usable);
513 $c->NEXT::dump_these(),
516 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
522 sub get_session_id { shift->NEXT::get_session_id(@_) }
523 sub set_session_id { shift->NEXT::set_session_id(@_) }
524 sub delete_session_id { shift->NEXT::delete_session_id(@_) }
525 sub extend_session_id { shift->NEXT::extend_session_id(@_) }
535 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
539 # To get sessions to "just work", all you need to do is use these plugins:
543 Session::Store::FastMmap
544 Session::State::Cookie
547 # you can replace Store::FastMmap with Store::File - both have sensible
548 # default configurations (see their docs for details)
550 # more complicated backends are available for other scenarios (DBI storage,
554 # after you've loaded the plugins you can save session data
555 # For example, if you are writing a shopping cart, it could be implemented
558 sub add_item : Local {
559 my ( $self, $c ) = @_;
561 my $item_id = $c->req->param("item");
563 # $c->session is a hash ref, a bit like $c->stash
564 # the difference is that it' preserved across requests
566 push @{ $c->session->{items} }, $item_id;
568 $c->forward("MyView");
571 sub display_items : Local {
572 my ( $self, $c ) = @_;
574 # values in $c->session are restored
575 $c->stash->{items_to_display} =
576 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
578 $c->forward("MyView");
583 The Session plugin is the base of two related parts of functionality required
584 for session management in web applications.
586 The first part, the State, is getting the browser to repeat back a session key,
587 so that the web application can identify the client and logically string
588 several requests together into a session.
590 The second part, the Store, deals with the actual storage of information about
591 the client. This data is stored so that the it may be revived for every request
592 made by the same client.
594 This plugin links the two pieces together.
596 =head1 RECOMENDED BACKENDS
600 =item Session::State::Cookie
602 The only really sane way to do state is using cookies.
604 =item Session::Store::File
606 A portable backend, based on Cache::File.
608 =item Session::Store::FastMmap
610 A fast and flexible backend, based on Cache::FastMmap.
620 An accessor for the session ID value.
624 Returns a hash reference that might contain unserialized values from previous
625 requests in the same session, and whose modified value will be saved for future
628 This method will automatically create a new session and session ID if none
631 =item session_expires
633 =item session_expires $reset
635 This method returns the time when the current session will expire, or 0 if
636 there is no current session. If there is a session and it already expired, it
637 will delete the session and return 0 as well.
639 If the C<$reset> parameter is true, and there is a session ID the expiry time
640 will be reset to the current time plus the time to live (see
641 L</CONFIGURATION>). This is used when creating a new session.
645 This is like Ruby on Rails' flash data structure. Think of it as a stash that
646 lasts for longer than one request, letting you redirect instead of forward.
648 The flash data will be cleaned up only on requests on which actually use
649 $c->flash (thus allowing multiple redirections), and the policy is to delete
650 all the keys which haven't changed since the flash data was loaded at the end
654 my ( $self, $c ) = @_;
656 $c->flash->{beans} = 10;
657 $c->response->redirect( $c->uri_for("foo") );
661 my ( $self, $c ) = @_;
663 my $value = $c->flash->{beans};
667 $c->response->redirect( $c->uri_for("bar") );
671 my ( $self, $c ) = @_;
673 if ( exists $c->flash->{beans} ) { # false
680 Zap all the keys in the flash regardless of their current state.
682 =item keep_flash @keys
684 If you want to keep a flash key for the next request too, even if it hasn't
685 changed, call C<keep_flash> and pass in the keys as arguments.
687 =item delete_session REASON
689 This method is used to invalidate a session. It takes an optional parameter
690 which will be saved in C<session_delete_reason> if provided.
692 =item session_delete_reason
694 This accessor contains a string with the reason a session was deleted. Possible
709 =item session_expire_key $key, $ttl
711 Mark a key to expire at a certain time (only useful when shorter than the
712 expiry time for the whole session).
716 __PACKAGE__->config->{session}{expires} = 1000000000000; # forever
720 $c->session_expire_key( __user => 3600 );
722 Will make the session data survive, but the user will still be logged out after
725 Note that these values are not auto extended.
729 =head1 INTERNAL METHODS
735 This method is extended to also make calls to
736 C<check_session_plugin_requirements> and C<setup_session>.
738 =item check_session_plugin_requirements
740 This method ensures that a State and a Store plugin are also in use by the
745 This method populates C<< $c->config->{session} >> with the default values
746 listed in L</CONFIGURATION>.
750 This method is extended.
752 Its only effect is if the (off by default) C<flash_to_stash> configuration
753 parameter is on - then it will copy the contents of the flash to the stash at
756 =item finalize_headers
758 This method is extended and will extend the expiry time before sending
763 This method is extended and will call finalize_session before the other
764 finalize_body methods run. Here we persist the session data if a session exists.
766 =item initialize_session_data
768 This method will initialize the internal structure of the session, and is
769 called by the C<session> method if appropriate.
771 =item create_session_id
773 Creates a new session ID using C<generate_session_id> if there is no session ID
776 =item validate_session_id SID
778 Make sure a session ID is of the right format.
780 This currently ensures that the session ID string is any amount of case
781 insensitive hexadecimal characters.
783 =item generate_session_id
785 This method will return a string that can be used as a session ID. It is
786 supposed to be a reasonably random string with enough bits to prevent
787 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
788 MD5 or SHA-256, depending on the availability of these modules.
790 =item session_hash_seed
792 This method is actually rather internal to generate_session_id, but should be
793 overridable in case you want to provide more random data.
795 Currently it returns a concatenated string which contains:
801 =item * The current time
803 =item * One value from C<rand>.
805 =item * The stringified value of a newly allocated hash reference
807 =item * The stringified value of the Catalyst context object
811 in the hopes that those combined values are entropic enough for most uses. If
812 this is not the case you can replace C<session_hash_seed> with e.g.
814 sub session_hash_seed {
815 open my $fh, "<", "/dev/random";
816 read $fh, my $bytes, 20;
821 Or even more directly, replace C<generate_session_id>:
823 sub generate_session_id {
824 open my $fh, "<", "/dev/random";
825 read $fh, my $bytes, 20;
827 return unpack("H*", $bytes);
830 Also have a look at L<Crypt::Random> and the various openssl bindings - these
831 modules provide APIs for cryptographically secure random data.
833 =item finalize_session
835 Clean up the session during C<finalize>.
837 This clears the various accessors after saving to the store.
841 See L<Catalyst/dump_these> - ammends the session data structure to the list of
842 dumped objects if session ID is defined.
845 =item calculate_extended_session_expires
847 =item calculate_initial_session_expires
849 =item create_session_id_if_needed
851 =item delete_session_id
853 =item extend_session_expires
855 =item extend_session_id
859 =item reset_session_expires
861 =item session_is_valid
867 =head1 USING SESSIONS DURING PREPARE
869 The earliest point in time at which you may use the session data is after
870 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
872 State plugins must set $c->session ID before C<prepare_action>, and during
873 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
879 # don't touch $c->session yet!
881 $c->NEXT::prepare_action( @_ );
883 $c->session; # this is OK
884 $c->sessionid; # this is also OK
889 $c->config->{session} = {
893 All configuation parameters are provided in a hash reference under the
894 C<session> key in the configuration hash.
900 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
905 When true, C<<$c->request->address>> will be checked at prepare time. If it is
906 not the same as the address that initiated the session, the session is deleted.
912 This option makes it easier to have actions behave the same whether they were
913 forwarded to or redirected to. On prepare time it copies the contents of
914 C<flash> (if any) to the stash.
920 The hash reference returned by C<< $c->session >> contains several keys which
921 are automatically set:
927 This key no longer exists. Use C<session_expires> instead.
931 The last time a session was saved to the store.
935 The time when the session was first created.
939 The value of C<< $c->request->address >> at the time the session was created.
940 This value is only populated if C<verify_address> is true in the configuration.
946 =head2 Round the Robin Proxies
948 C<verify_address> could make your site inaccessible to users who are behind
949 load balanced proxies. Some ISPs may give a different IP to each request by the
950 same client due to this type of proxying. If addresses are verified these
951 users' sessions cannot persist.
953 To let these users access your site you can either disable address verification
954 as a whole, or provide a checkbox in the login dialog that tells the server
955 that it's OK for the address of the client to change. When the server sees that
956 this box is checked it should delete the C<__address> special key from the
957 session hash when the hash is first created.
959 =head2 Race Conditions
961 In this day and age where cleaning detergents and Dutch football (not the
962 American kind) teams roam the plains in great numbers, requests may happen
963 simultaneously. This means that there is some risk of session data being
964 overwritten, like this:
970 request a starts, request b starts, with the same session ID
974 session data is loaded in request a
978 session data is loaded in request b
982 session data is changed in request a
986 request a finishes, session data is updated and written to store
990 request b finishes, session data is updated and written to store, overwriting
995 If this is a concern in your application, a soon-to-be-developed locking
996 solution is the only safe way to go. This will have a bigger overhead.
998 For applications where any given user is only making one request at a time this
999 plugin should be safe enough.
1007 Yuval Kogman, C<nothingmuch@woobling.org> (current maintainer)
1011 And countless other contributers from #catalyst. Thanks guys!
1013 =head1 COPYRIGHT & LICENSE
1015 Copyright (c) 2005 the aforementioned authors. All rights
1016 reserved. This program is free software; you can redistribute
1017 it and/or modify it under the same terms as Perl itself.