3 package Catalyst::Plugin::Session;
6 with 'MooseX::Emulate::Class::Accessor::Fast';
8 use Catalyst::Exception ();
11 use Object::Signature ();
14 use namespace::clean -except => 'meta';
16 our $VERSION = '0.37';
17 $VERSION = eval $VERSION;
19 my @session_data_accessors; # used in delete_session
21 __PACKAGE__->mk_accessors(
22 "_session_delete_reason",
23 @session_data_accessors = qw/
27 _extended_session_expires
32 _tried_loading_session_id
33 _tried_loading_session_data
34 _tried_loading_session_expires
35 _tried_loading_flash_data
39 sub _session_plugin_config {
41 # FIXME - Start warning once all the state/store modules have also been updated.
42 #$c->log->warn("Deprecated 'session' config key used, please use the key 'Plugin::Session' instead")
43 # if exists $c->config->{session}
44 #$c->config->{'Plugin::Session'} ||= delete($c->config->{session}) || {};
45 $c->config->{'Plugin::Session'} ||= $c->config->{session} || {};
51 $c->maybe::next::method(@_);
53 $c->check_session_plugin_requirements;
59 sub check_session_plugin_requirements {
62 unless ( $c->isa("Catalyst::Plugin::Session::State")
63 && $c->isa("Catalyst::Plugin::Session::Store") )
66 ( "The Session plugin requires both Session::State "
67 . "and Session::Store plugins to be used as well." );
70 Catalyst::Exception->throw($err);
77 my $cfg = $c->_session_plugin_config;
82 verify_user_agent => 0,
86 $c->maybe::next::method();
92 $c->maybe::next::method(@_);
94 if ( $c->_session_plugin_config->{flash_to_stash}
96 and my $flash_data = $c->flash )
98 @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
102 sub finalize_headers {
105 # fix cookie before we send headers
106 $c->_save_session_expires;
108 # Force extension of session_expires before finalizing headers, so a pos
109 # up to date. First call to session_expires will extend the expiry, subs
110 # just return the previously extended value.
113 return $c->maybe::next::method(@_);
119 # We have to finalize our session *before* $c->engine->finalize_xxx is called,
120 # because we do not want to send the HTTP response before the session is stored/committed to
121 # the session database (or whatever Session::Store you use).
122 $c->finalize_session;
124 return $c->maybe::next::method(@_);
127 sub finalize_session {
130 $c->maybe::next::method(@_);
132 $c->_save_session_id;
136 $c->_clear_session_instance_data;
139 sub _save_session_id {
142 # we already called set when allocating
143 # no need to tell the state plugins anything new
146 sub _save_session_expires {
149 if ( defined($c->_session_expires) ) {
150 my $expires = $c->session_expires; # force extension
152 my $sid = $c->sessionid;
153 $c->store_session_data( "expires:$sid" => $expires );
160 if ( my $session_data = $c->_session ) {
162 no warnings 'uninitialized';
163 if ( Object::Signature::signature($session_data) ne
164 $c->_session_data_sig )
166 $session_data->{__updated} = time();
167 my $sid = $c->sessionid;
168 $c->store_session_data( "session:$sid" => $session_data );
176 if ( my $flash_data = $c->_flash ) {
178 my $hashes = $c->_flash_key_hashes || {};
179 my $keep = $c->_flash_keep_keys || {};
180 foreach my $key ( keys %$hashes ) {
181 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
182 delete $flash_data->{$key};
186 my $sid = $c->sessionid;
188 my $session_data = $c->_session;
190 $session_data->{__flash} = $flash_data;
193 delete $session_data->{__flash};
195 $c->_session($session_data);
200 sub _load_session_expires {
202 return $c->_session_expires if $c->_tried_loading_session_expires;
203 $c->_tried_loading_session_expires(1);
205 if ( my $sid = $c->sessionid ) {
206 my $expires = $c->get_session_data("expires:$sid") || 0;
208 if ( $expires >= time() ) {
209 $c->_session_expires( $expires );
212 $c->delete_session( "session expired" );
222 return $c->_session if $c->_tried_loading_session_data;
223 $c->_tried_loading_session_data(1);
225 if ( my $sid = $c->sessionid ) {
226 if ( $c->_load_session_expires ) { # > 0
228 my $session_data = $c->get_session_data("session:$sid") || return;
229 $c->_session($session_data);
231 no warnings 'uninitialized'; # ne __address
232 if ( $c->_session_plugin_config->{verify_address}
233 && exists $session_data->{__address}
234 && $session_data->{__address} ne $c->request->address )
237 "Deleting session $sid due to address mismatch ("
238 . $session_data->{__address} . " != "
239 . $c->request->address . ")"
241 $c->delete_session("address mismatch");
244 if ( $c->_session_plugin_config->{verify_user_agent}
245 && $session_data->{__user_agent} ne $c->request->user_agent )
248 "Deleting session $sid due to user agent mismatch ("
249 . $session_data->{__user_agent} . " != "
250 . $c->request->user_agent . ")"
252 $c->delete_session("user agent mismatch");
256 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
257 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
258 $c->_expire_session_keys;
260 return $session_data;
269 return $c->_flash if $c->_tried_loading_flash_data;
270 $c->_tried_loading_flash_data(1);
272 if ( my $sid = $c->sessionid ) {
274 my $session_data = $c->session;
275 $c->_flash($session_data->{__flash});
277 if ( my $flash_data = $c->_flash )
279 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
288 sub _expire_session_keys {
289 my ( $c, $data ) = @_;
293 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
294 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
295 delete $c->_session->{$key};
296 delete $expire_times->{$key};
300 sub _clear_session_instance_data {
302 $c->$_(undef) for @session_data_accessors;
303 $c->maybe::next::method(@_); # allow other plugins to hook in on this
306 sub change_session_id {
309 my $sessiondata = $c->session;
310 my $oldsid = $c->sessionid;
311 my $newsid = $c->create_session_id;
314 $c->log->debug(qq/change_sessid: deleting session data from "$oldsid"/) if $c->debug;
315 $c->delete_session_data("${_}:${oldsid}") for qw/session expires flash/;
318 $c->log->debug(qq/change_sessid: storing session data to "$newsid"/) if $c->debug;
319 $c->store_session_data( "session:$newsid" => $sessiondata );
325 my ( $c, $msg ) = @_;
327 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
329 # delete the session data
330 if ( my $sid = $c->sessionid ) {
331 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
332 $c->delete_session_id($sid);
335 # reset the values in the context object
336 # see the BEGIN block
337 $c->_clear_session_instance_data;
339 $c->_session_delete_reason($msg);
342 sub session_delete_reason {
345 $c->session_is_valid; # check that it was loaded
347 $c->_session_delete_reason(@_);
350 sub session_expires {
353 if ( defined( my $expires = $c->_extended_session_expires ) ) {
355 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
356 return $c->extend_session_expires( $expires );
362 sub extend_session_expires {
363 my ( $c, $expires ) = @_;
364 $c->_extended_session_expires( my $updated = $c->calculate_initial_session_expires( $expires ) );
365 $c->extend_session_id( $c->sessionid, $updated );
369 sub change_session_expires {
370 my ( $c, $expires ) = @_;
373 my $sid = $c->sessionid;
374 my $time_exp = time() + $expires;
375 $c->store_session_data( "expires:$sid" => $time_exp );
378 sub initial_session_expires {
380 return ( time() + $c->_session_plugin_config->{expires} );
383 sub calculate_initial_session_expires {
386 my $initial_expires = $c->initial_session_expires;
387 my $stored_session_expires = 0;
388 if ( my $sid = $c->sessionid ) {
389 $stored_session_expires = $c->get_session_data("expires:$sid") || 0;
391 return ( $initial_expires > $stored_session_expires ) ? $initial_expires : $stored_session_expires;
394 sub calculate_extended_session_expires {
395 my ( $c, $prev ) = @_;
396 return ( time() + $prev );
399 sub reset_session_expires {
400 my ( $c, $sid ) = @_;
402 my $exp = $c->calculate_initial_session_expires;
403 $c->_session_expires( $exp );
405 # since we're setting _session_expires directly, make load_session_expires
406 # actually use that value.
408 $c->_tried_loading_session_expires(1);
409 $c->_extended_session_expires( $exp );
416 return $c->_sessionid || $c->_load_sessionid;
419 sub _load_sessionid {
421 return if $c->_tried_loading_session_id;
422 $c->_tried_loading_session_id(1);
424 if ( defined( my $sid = $c->get_session_id ) ) {
425 if ( $c->validate_session_id($sid) ) {
426 # temporarily set the inner key, so that validation will work
427 $c->_sessionid($sid);
430 my $err = "Tried to set invalid session ID '$sid'";
431 $c->log->error($err);
432 Catalyst::Exception->throw($err);
439 sub session_is_valid {
442 # force a check for expiry, but also __address, etc
443 if ( $c->_load_session ) {
450 sub validate_session_id {
451 my ( $c, $sid ) = @_;
453 $sid and $sid =~ /^[a-f\d]+$/i;
459 my $session = $c->_session || $c->_load_session || do {
460 $c->create_session_id_if_needed;
461 $c->initialize_session_data;
465 my $new_values = @_ > 1 ? { @_ } : $_[0];
466 croak('session takes a hash or hashref') unless ref $new_values;
468 for my $key (keys %$new_values) {
469 $session->{$key} = $new_values->{$key};
477 my ( $c, @keys ) = @_;
478 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
479 (@{$href}{@keys}) = ((undef) x @keys);
484 $c->_flash || $c->_load_flash || do {
485 $c->create_session_id_if_needed;
493 my $items = @_ > 1 ? {@_} : $_[0];
494 croak('flash takes a hash or hashref') unless ref $items;
495 @{ $c->_flash }{ keys %$items } = values %$items;
509 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
510 $c->_flash_key_hashes({});
511 $c->_flash_keep_keys({});
515 sub session_expire_key {
516 my ( $c, %keys ) = @_;
519 @{ $c->session->{__expire_keys} }{ keys %keys } =
520 map { $now + $_ } values %keys;
523 sub initialize_session_data {
534 $c->_session_plugin_config->{verify_address}
535 ? ( __address => $c->request->address||'' )
539 $c->_session_plugin_config->{verify_user_agent}
540 ? ( __user_agent => $c->request->user_agent||'' )
547 sub generate_session_id {
550 my $digest = $c->_find_digest();
551 $digest->add( $c->session_hash_seed() );
552 return $digest->hexdigest;
555 sub create_session_id_if_needed {
557 $c->create_session_id unless $c->sessionid;
560 sub create_session_id {
563 my $sid = $c->generate_session_id;
565 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
567 $c->_sessionid($sid);
568 $c->reset_session_expires;
569 $c->set_session_id($sid);
576 sub session_hash_seed {
579 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
584 sub _find_digest () {
586 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
587 if ( eval { Digest->new($alg) } ) {
592 Catalyst::Exception->throw(
593 "Could not find a suitable Digest module. Please install "
594 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
598 return Digest->new($usable);
605 $c->maybe::next::method(),
608 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
614 sub get_session_id { shift->maybe::next::method(@_) }
615 sub set_session_id { shift->maybe::next::method(@_) }
616 sub delete_session_id { shift->maybe::next::method(@_) }
617 sub extend_session_id { shift->maybe::next::method(@_) }
627 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
631 # To get sessions to "just work", all you need to do is use these plugins:
635 Session::Store::FastMmap
636 Session::State::Cookie
639 # you can replace Store::FastMmap with Store::File - both have sensible
640 # default configurations (see their docs for details)
642 # more complicated backends are available for other scenarios (DBI storage,
646 # after you've loaded the plugins you can save session data
647 # For example, if you are writing a shopping cart, it could be implemented
650 sub add_item : Local {
651 my ( $self, $c ) = @_;
653 my $item_id = $c->req->param("item");
655 # $c->session is a hash ref, a bit like $c->stash
656 # the difference is that it' preserved across requests
658 push @{ $c->session->{items} }, $item_id;
660 $c->forward("MyView");
663 sub display_items : Local {
664 my ( $self, $c ) = @_;
666 # values in $c->session are restored
667 $c->stash->{items_to_display} =
668 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
670 $c->forward("MyView");
675 The Session plugin is the base of two related parts of functionality required
676 for session management in web applications.
678 The first part, the State, is getting the browser to repeat back a session key,
679 so that the web application can identify the client and logically string
680 several requests together into a session.
682 The second part, the Store, deals with the actual storage of information about
683 the client. This data is stored so that the it may be revived for every request
684 made by the same client.
686 This plugin links the two pieces together.
688 =head1 RECOMENDED BACKENDS
692 =item Session::State::Cookie
694 The only really sane way to do state is using cookies.
696 =item Session::Store::File
698 A portable backend, based on Cache::File.
700 =item Session::Store::FastMmap
702 A fast and flexible backend, based on Cache::FastMmap.
712 An accessor for the session ID value.
716 Returns a hash reference that might contain unserialized values from previous
717 requests in the same session, and whose modified value will be saved for future
720 This method will automatically create a new session and session ID if none
723 You can also set session keys by passing a list of key/value pairs or a
726 $c->session->{foo} = "bar"; # This works.
727 $c->session(one => 1, two => 2); # And this.
728 $c->session({ answer => 42 }); # And this.
730 =item session_expires
732 This method returns the time when the current session will expire, or 0 if
733 there is no current session. If there is a session and it already expired, it
734 will delete the session and return 0 as well.
738 This is like Ruby on Rails' flash data structure. Think of it as a stash that
739 lasts for longer than one request, letting you redirect instead of forward.
741 The flash data will be cleaned up only on requests on which actually use
742 $c->flash (thus allowing multiple redirections), and the policy is to delete
743 all the keys which haven't changed since the flash data was loaded at the end
746 Note that use of the flash is an easy way to get data across requests, but
747 it's also strongly disrecommended, due it it being inherently plagued with
748 race conditions. This means that it's unlikely to work well if your
749 users have multiple tabs open at once, or if your site does a lot of AJAX
752 L<Catalyst::Plugin::StatusMessage> is the recommended alternative solution,
753 as this doesn't suffer from these issues.
756 my ( $self, $c ) = @_;
758 $c->flash->{beans} = 10;
759 $c->response->redirect( $c->uri_for("foo") );
763 my ( $self, $c ) = @_;
765 my $value = $c->flash->{beans};
769 $c->response->redirect( $c->uri_for("bar") );
773 my ( $self, $c ) = @_;
775 if ( exists $c->flash->{beans} ) { # false
782 Zap all the keys in the flash regardless of their current state.
784 =item keep_flash @keys
786 If you want to keep a flash key for the next request too, even if it hasn't
787 changed, call C<keep_flash> and pass in the keys as arguments.
789 =item delete_session REASON
791 This method is used to invalidate a session. It takes an optional parameter
792 which will be saved in C<session_delete_reason> if provided.
794 NOTE: This method will B<also> delete your flash data.
796 =item session_delete_reason
798 This accessor contains a string with the reason a session was deleted. Possible
813 =item session_expire_key $key, $ttl
815 Mark a key to expire at a certain time (only useful when shorter than the
816 expiry time for the whole session).
820 __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # "forever"
821 (NB If this number is too large, Y2K38 breakage could result.)
825 $c->session_expire_key( __user => 3600 );
827 Will make the session data survive, but the user will still be logged out after
830 Note that these values are not auto extended.
832 =item change_session_id
834 By calling this method you can force a session id change while keeping all
835 session data. This method might come handy when you are paranoid about some
836 advanced variations of session fixation attack.
838 If you want to prevent this session fixation scenario:
840 0) let us have WebApp with anonymous and authenticated parts
841 1) a hacker goes to vulnerable WebApp and gets a real sessionid,
842 just by browsing anonymous part of WebApp
843 2) the hacker inserts (somehow) this values into a cookie in victim's browser
844 3) after the victim logs into WebApp the hacker can enter his/her session
846 you should call change_session_id in your login controller like this:
848 if ($c->authenticate( { username => $user, password => $pass } )) {
850 $c->change_session_id;
857 =item change_session_expires $expires
859 You can change the session expiration time for this session;
861 $c->change_session_expires( 4000 );
863 Note that this only works to set the session longer than the config setting.
867 =head1 INTERNAL METHODS
873 This method is extended to also make calls to
874 C<check_session_plugin_requirements> and C<setup_session>.
876 =item check_session_plugin_requirements
878 This method ensures that a State and a Store plugin are also in use by the
883 This method populates C<< $c->config('Plugin::Session') >> with the default values
884 listed in L</CONFIGURATION>.
888 This method is extended.
890 Its only effect is if the (off by default) C<flash_to_stash> configuration
891 parameter is on - then it will copy the contents of the flash to the stash at
894 =item finalize_headers
896 This method is extended and will extend the expiry time before sending
901 This method is extended and will call finalize_session before the other
902 finalize_body methods run. Here we persist the session data if a session exists.
904 =item initialize_session_data
906 This method will initialize the internal structure of the session, and is
907 called by the C<session> method if appropriate.
909 =item create_session_id
911 Creates a new session ID using C<generate_session_id> if there is no session ID
914 =item validate_session_id SID
916 Make sure a session ID is of the right format.
918 This currently ensures that the session ID string is any amount of case
919 insensitive hexadecimal characters.
921 =item generate_session_id
923 This method will return a string that can be used as a session ID. It is
924 supposed to be a reasonably random string with enough bits to prevent
925 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
926 MD5 or SHA-256, depending on the availability of these modules.
928 =item session_hash_seed
930 This method is actually rather internal to generate_session_id, but should be
931 overridable in case you want to provide more random data.
933 Currently it returns a concatenated string which contains:
939 =item * The current time
941 =item * One value from C<rand>.
943 =item * The stringified value of a newly allocated hash reference
945 =item * The stringified value of the Catalyst context object
949 in the hopes that those combined values are entropic enough for most uses. If
950 this is not the case you can replace C<session_hash_seed> with e.g.
952 sub session_hash_seed {
953 open my $fh, "<", "/dev/random";
954 read $fh, my $bytes, 20;
959 Or even more directly, replace C<generate_session_id>:
961 sub generate_session_id {
962 open my $fh, "<", "/dev/random";
963 read $fh, my $bytes, 20;
965 return unpack("H*", $bytes);
968 Also have a look at L<Crypt::Random> and the various openssl bindings - these
969 modules provide APIs for cryptographically secure random data.
971 =item finalize_session
973 Clean up the session during C<finalize>.
975 This clears the various accessors after saving to the store.
979 See L<Catalyst/dump_these> - ammends the session data structure to the list of
980 dumped objects if session ID is defined.
983 =item calculate_extended_session_expires
985 =item calculate_initial_session_expires
987 =item create_session_id_if_needed
989 =item delete_session_id
991 =item extend_session_expires
993 Note: this is *not* used to give an individual user a longer session. See
994 'change_session_expires'.
996 =item extend_session_id
1000 =item reset_session_expires
1002 =item session_is_valid
1004 =item set_session_id
1006 =item initial_session_expires
1010 =head1 USING SESSIONS DURING PREPARE
1012 The earliest point in time at which you may use the session data is after
1013 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
1015 State plugins must set $c->session ID before C<prepare_action>, and during
1016 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
1019 sub prepare_action {
1022 # don't touch $c->session yet!
1024 $c->NEXT::prepare_action( @_ );
1026 $c->session; # this is OK
1027 $c->sessionid; # this is also OK
1030 =head1 CONFIGURATION
1032 $c->config('Plugin::Session' => {
1036 All configuation parameters are provided in a hash reference under the
1037 C<Plugin::Session> key in the configuration hash.
1043 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
1046 =item verify_address
1048 When true, C<<$c->request->address>> will be checked at prepare time. If it is
1049 not the same as the address that initiated the session, the session is deleted.
1053 =item verify_user_agent
1055 When true, C<<$c->request->user_agent>> will be checked at prepare time. If it
1056 is not the same as the user agent that initiated the session, the session is
1061 =item flash_to_stash
1063 This option makes it easier to have actions behave the same whether they were
1064 forwarded to or redirected to. On prepare time it copies the contents of
1065 C<flash> (if any) to the stash.
1071 The hash reference returned by C<< $c->session >> contains several keys which
1072 are automatically set:
1078 This key no longer exists. Use C<session_expires> instead.
1082 The last time a session was saved to the store.
1086 The time when the session was first created.
1090 The value of C<< $c->request->address >> at the time the session was created.
1091 This value is only populated if C<verify_address> is true in the configuration.
1095 The value of C<< $c->request->user_agent >> at the time the session was created.
1096 This value is only populated if C<verify_user_agent> is true in the configuration.
1102 =head2 Round the Robin Proxies
1104 C<verify_address> could make your site inaccessible to users who are behind
1105 load balanced proxies. Some ISPs may give a different IP to each request by the
1106 same client due to this type of proxying. If addresses are verified these
1107 users' sessions cannot persist.
1109 To let these users access your site you can either disable address verification
1110 as a whole, or provide a checkbox in the login dialog that tells the server
1111 that it's OK for the address of the client to change. When the server sees that
1112 this box is checked it should delete the C<__address> special key from the
1113 session hash when the hash is first created.
1115 =head2 Race Conditions
1117 In this day and age where cleaning detergents and Dutch football (not the
1118 American kind) teams roam the plains in great numbers, requests may happen
1119 simultaneously. This means that there is some risk of session data being
1120 overwritten, like this:
1126 request a starts, request b starts, with the same session ID
1130 session data is loaded in request a
1134 session data is loaded in request b
1138 session data is changed in request a
1142 request a finishes, session data is updated and written to store
1146 request b finishes, session data is updated and written to store, overwriting
1147 changes by request a
1151 For applications where any given user's session is only making one request
1152 at a time this plugin should be safe enough.
1160 Yuval Kogman, C<nothingmuch@woobling.org>
1164 Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)
1170 Florian Ragwitz (rafl) C<rafl@debian.org>
1172 Kent Fredric (kentnl)
1174 And countless other contributers from #catalyst. Thanks guys!
1178 Devin Austin (dhoss) <dhoss@cpan.org>
1180 =head1 COPYRIGHT & LICENSE
1182 Copyright (c) 2005 the aforementioned authors. All rights
1183 reserved. This program is free software; you can redistribute
1184 it and/or modify it under the same terms as Perl itself.