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,
83 expiry_threshold => 0,
87 $c->maybe::next::method();
93 $c->maybe::next::method(@_);
95 if ( $c->_session_plugin_config->{flash_to_stash}
97 and my $flash_data = $c->flash )
99 @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
103 sub finalize_headers {
106 # fix cookie before we send headers
107 $c->_save_session_expires;
109 # Force extension of session_expires before finalizing headers, so a pos
110 # up to date. First call to session_expires will extend the expiry, subs
111 # just return the previously extended value.
114 return $c->maybe::next::method(@_);
120 # We have to finalize our session *before* $c->engine->finalize_xxx is called,
121 # because we do not want to send the HTTP response before the session is stored/committed to
122 # the session database (or whatever Session::Store you use).
123 $c->finalize_session;
125 return $c->maybe::next::method(@_);
128 sub finalize_session {
131 $c->maybe::next::method(@_);
133 $c->_save_session_id;
137 $c->_clear_session_instance_data;
140 sub _save_session_id {
143 # we already called set when allocating
144 # no need to tell the state plugins anything new
147 sub _save_session_expires {
150 if ( defined($c->_session_expires) ) {
152 my $threshold = $c->_session_plugin_config->{expiry_threshold} || 0;
154 if ( my $sid = $c->sessionid ) {
155 my $cutoff = ( $c->get_session_data("expires:$sid") || 0 ) - $threshold;
157 if (!$threshold || $cutoff <= time) {
158 my $expires = $c->session_expires; # force extension
159 $c->store_session_data( "expires:$sid" => $expires );
171 if ( my $session_data = $c->_session ) {
173 no warnings 'uninitialized';
174 if ( Object::Signature::signature($session_data) ne
175 $c->_session_data_sig )
177 $session_data->{__updated} = time();
178 my $sid = $c->sessionid;
179 $c->store_session_data( "session:$sid" => $session_data );
187 if ( my $flash_data = $c->_flash ) {
189 my $hashes = $c->_flash_key_hashes || {};
190 my $keep = $c->_flash_keep_keys || {};
191 foreach my $key ( keys %$hashes ) {
192 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
193 delete $flash_data->{$key};
197 my $sid = $c->sessionid;
199 my $session_data = $c->_session;
201 $session_data->{__flash} = $flash_data;
204 delete $session_data->{__flash};
206 $c->_session($session_data);
211 sub _load_session_expires {
213 return $c->_session_expires if $c->_tried_loading_session_expires;
214 $c->_tried_loading_session_expires(1);
216 if ( my $sid = $c->sessionid ) {
217 my $expires = $c->get_session_data("expires:$sid") || 0;
219 if ( $expires >= time() ) {
220 $c->_session_expires( $expires );
223 $c->delete_session( "session expired" );
233 return $c->_session if $c->_tried_loading_session_data;
234 $c->_tried_loading_session_data(1);
236 if ( my $sid = $c->sessionid ) {
237 if ( $c->_load_session_expires ) { # > 0
239 my $session_data = $c->get_session_data("session:$sid") || return;
240 $c->_session($session_data);
242 no warnings 'uninitialized'; # ne __address
243 if ( $c->_session_plugin_config->{verify_address}
244 && exists $session_data->{__address}
245 && $session_data->{__address} ne $c->request->address )
248 "Deleting session $sid due to address mismatch ("
249 . $session_data->{__address} . " != "
250 . $c->request->address . ")"
252 $c->delete_session("address mismatch");
255 if ( $c->_session_plugin_config->{verify_user_agent}
256 && $session_data->{__user_agent} ne $c->request->user_agent )
259 "Deleting session $sid due to user agent mismatch ("
260 . $session_data->{__user_agent} . " != "
261 . $c->request->user_agent . ")"
263 $c->delete_session("user agent mismatch");
267 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
268 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
269 $c->_expire_session_keys;
271 return $session_data;
280 return $c->_flash if $c->_tried_loading_flash_data;
281 $c->_tried_loading_flash_data(1);
283 if ( my $sid = $c->sessionid ) {
285 my $session_data = $c->session;
286 $c->_flash($session_data->{__flash});
288 if ( my $flash_data = $c->_flash )
290 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
299 sub _expire_session_keys {
300 my ( $c, $data ) = @_;
304 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
305 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
306 delete $c->_session->{$key};
307 delete $expire_times->{$key};
311 sub _clear_session_instance_data {
313 $c->$_(undef) for @session_data_accessors;
314 $c->maybe::next::method(@_); # allow other plugins to hook in on this
317 sub change_session_id {
320 my $sessiondata = $c->session;
321 my $oldsid = $c->sessionid;
322 my $newsid = $c->create_session_id;
325 $c->log->debug(qq/change_sessid: deleting session data from "$oldsid"/) if $c->debug;
326 $c->delete_session_data("${_}:${oldsid}") for qw/session expires flash/;
329 $c->log->debug(qq/change_sessid: storing session data to "$newsid"/) if $c->debug;
330 $c->store_session_data( "session:$newsid" => $sessiondata );
336 my ( $c, $msg ) = @_;
338 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
340 # delete the session data
341 if ( my $sid = $c->sessionid ) {
342 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
343 $c->delete_session_id($sid);
346 # reset the values in the context object
347 # see the BEGIN block
348 $c->_clear_session_instance_data;
350 $c->_session_delete_reason($msg);
353 sub session_delete_reason {
356 $c->session_is_valid; # check that it was loaded
358 $c->_session_delete_reason(@_);
361 sub session_expires {
364 if ( defined( my $expires = $c->_extended_session_expires ) ) {
366 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
367 return $c->extend_session_expires( $expires );
373 sub extend_session_expires {
374 my ( $c, $expires ) = @_;
375 $c->_extended_session_expires( my $updated = $c->calculate_initial_session_expires() );
376 $c->extend_session_id( $c->sessionid, $updated );
380 sub change_session_expires {
381 my ( $c, $expires ) = @_;
384 my $sid = $c->sessionid;
385 my $time_exp = time() + $expires;
386 $c->store_session_data( "expires:$sid" => $time_exp );
389 sub initial_session_expires {
391 return ( time() + $c->_session_plugin_config->{expires} );
394 sub calculate_initial_session_expires {
397 my $initial_expires = $c->initial_session_expires;
398 my $stored_session_expires = 0;
399 if ( my $sid = $c->sessionid ) {
400 $stored_session_expires = $c->get_session_data("expires:$sid") || 0;
402 return ( $initial_expires > $stored_session_expires ) ? $initial_expires : $stored_session_expires;
405 sub calculate_extended_session_expires {
406 my ( $c, $prev ) = @_;
407 return ( time() + $prev );
410 sub reset_session_expires {
411 my ( $c, $sid ) = @_;
413 my $exp = $c->calculate_initial_session_expires;
414 $c->_session_expires( $exp );
416 # since we're setting _session_expires directly, make load_session_expires
417 # actually use that value.
419 $c->_tried_loading_session_expires(1);
420 $c->_extended_session_expires( $exp );
427 return $c->_sessionid || $c->_load_sessionid;
430 sub _load_sessionid {
432 return if $c->_tried_loading_session_id;
433 $c->_tried_loading_session_id(1);
435 if ( defined( my $sid = $c->get_session_id ) ) {
436 if ( $c->validate_session_id($sid) ) {
437 # temporarily set the inner key, so that validation will work
438 $c->_sessionid($sid);
441 my $err = "Tried to set invalid session ID '$sid'";
442 $c->log->error($err);
443 Catalyst::Exception->throw($err);
450 sub session_is_valid {
453 # force a check for expiry, but also __address, etc
454 if ( $c->_load_session ) {
461 sub validate_session_id {
462 my ( $c, $sid ) = @_;
464 $sid and $sid =~ /^[a-f\d]+$/i;
470 my $session = $c->_session || $c->_load_session || do {
471 $c->create_session_id_if_needed;
472 $c->initialize_session_data;
476 my $new_values = @_ > 1 ? { @_ } : $_[0];
477 croak('session takes a hash or hashref') unless ref $new_values;
479 for my $key (keys %$new_values) {
480 $session->{$key} = $new_values->{$key};
488 my ( $c, @keys ) = @_;
489 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
490 (@{$href}{@keys}) = ((undef) x @keys);
495 $c->_flash || $c->_load_flash || do {
496 $c->create_session_id_if_needed;
504 my $items = @_ > 1 ? {@_} : $_[0];
505 croak('flash takes a hash or hashref') unless ref $items;
506 @{ $c->_flash }{ keys %$items } = values %$items;
520 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
521 $c->_flash_key_hashes({});
522 $c->_flash_keep_keys({});
526 sub session_expire_key {
527 my ( $c, %keys ) = @_;
530 @{ $c->session->{__expire_keys} }{ keys %keys } =
531 map { $now + $_ } values %keys;
534 sub initialize_session_data {
545 $c->_session_plugin_config->{verify_address}
546 ? ( __address => $c->request->address||'' )
550 $c->_session_plugin_config->{verify_user_agent}
551 ? ( __user_agent => $c->request->user_agent||'' )
558 sub generate_session_id {
561 my $digest = $c->_find_digest();
562 $digest->add( $c->session_hash_seed() );
563 return $digest->hexdigest;
566 sub create_session_id_if_needed {
568 $c->create_session_id unless $c->sessionid;
571 sub create_session_id {
574 my $sid = $c->generate_session_id;
576 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
578 $c->_sessionid($sid);
579 $c->reset_session_expires;
580 $c->set_session_id($sid);
587 sub session_hash_seed {
590 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
595 sub _find_digest () {
597 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
598 if ( eval { Digest->new($alg) } ) {
603 Catalyst::Exception->throw(
604 "Could not find a suitable Digest module. Please install "
605 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
609 return Digest->new($usable);
616 $c->maybe::next::method(),
619 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
625 sub get_session_id { shift->maybe::next::method(@_) }
626 sub set_session_id { shift->maybe::next::method(@_) }
627 sub delete_session_id { shift->maybe::next::method(@_) }
628 sub extend_session_id { shift->maybe::next::method(@_) }
638 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
642 # To get sessions to "just work", all you need to do is use these plugins:
646 Session::Store::FastMmap
647 Session::State::Cookie
650 # you can replace Store::FastMmap with Store::File - both have sensible
651 # default configurations (see their docs for details)
653 # more complicated backends are available for other scenarios (DBI storage,
657 # after you've loaded the plugins you can save session data
658 # For example, if you are writing a shopping cart, it could be implemented
661 sub add_item : Local {
662 my ( $self, $c ) = @_;
664 my $item_id = $c->req->param("item");
666 # $c->session is a hash ref, a bit like $c->stash
667 # the difference is that it' preserved across requests
669 push @{ $c->session->{items} }, $item_id;
671 $c->forward("MyView");
674 sub display_items : Local {
675 my ( $self, $c ) = @_;
677 # values in $c->session are restored
678 $c->stash->{items_to_display} =
679 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
681 $c->forward("MyView");
686 The Session plugin is the base of two related parts of functionality required
687 for session management in web applications.
689 The first part, the State, is getting the browser to repeat back a session key,
690 so that the web application can identify the client and logically string
691 several requests together into a session.
693 The second part, the Store, deals with the actual storage of information about
694 the client. This data is stored so that the it may be revived for every request
695 made by the same client.
697 This plugin links the two pieces together.
699 =head1 RECOMENDED BACKENDS
703 =item Session::State::Cookie
705 The only really sane way to do state is using cookies.
707 =item Session::Store::File
709 A portable backend, based on Cache::File.
711 =item Session::Store::FastMmap
713 A fast and flexible backend, based on Cache::FastMmap.
723 An accessor for the session ID value.
727 Returns a hash reference that might contain unserialized values from previous
728 requests in the same session, and whose modified value will be saved for future
731 This method will automatically create a new session and session ID if none
734 You can also set session keys by passing a list of key/value pairs or a
737 $c->session->{foo} = "bar"; # This works.
738 $c->session(one => 1, two => 2); # And this.
739 $c->session({ answer => 42 }); # And this.
741 =item session_expires
743 This method returns the time when the current session will expire, or 0 if
744 there is no current session. If there is a session and it already expired, it
745 will delete the session and return 0 as well.
749 This is like Ruby on Rails' flash data structure. Think of it as a stash that
750 lasts for longer than one request, letting you redirect instead of forward.
752 The flash data will be cleaned up only on requests on which actually use
753 $c->flash (thus allowing multiple redirections), and the policy is to delete
754 all the keys which haven't changed since the flash data was loaded at the end
757 Note that use of the flash is an easy way to get data across requests, but
758 it's also strongly disrecommended, due it it being inherently plagued with
759 race conditions. This means that it's unlikely to work well if your
760 users have multiple tabs open at once, or if your site does a lot of AJAX
763 L<Catalyst::Plugin::StatusMessage> is the recommended alternative solution,
764 as this doesn't suffer from these issues.
767 my ( $self, $c ) = @_;
769 $c->flash->{beans} = 10;
770 $c->response->redirect( $c->uri_for("foo") );
774 my ( $self, $c ) = @_;
776 my $value = $c->flash->{beans};
780 $c->response->redirect( $c->uri_for("bar") );
784 my ( $self, $c ) = @_;
786 if ( exists $c->flash->{beans} ) { # false
793 Zap all the keys in the flash regardless of their current state.
795 =item keep_flash @keys
797 If you want to keep a flash key for the next request too, even if it hasn't
798 changed, call C<keep_flash> and pass in the keys as arguments.
800 =item delete_session REASON
802 This method is used to invalidate a session. It takes an optional parameter
803 which will be saved in C<session_delete_reason> if provided.
805 NOTE: This method will B<also> delete your flash data.
807 =item session_delete_reason
809 This accessor contains a string with the reason a session was deleted. Possible
824 =item session_expire_key $key, $ttl
826 Mark a key to expire at a certain time (only useful when shorter than the
827 expiry time for the whole session).
831 __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # "forever"
832 (NB If this number is too large, Y2K38 breakage could result.)
836 $c->session_expire_key( __user => 3600 );
838 Will make the session data survive, but the user will still be logged out after
841 Note that these values are not auto extended.
843 =item change_session_id
845 By calling this method you can force a session id change while keeping all
846 session data. This method might come handy when you are paranoid about some
847 advanced variations of session fixation attack.
849 If you want to prevent this session fixation scenario:
851 0) let us have WebApp with anonymous and authenticated parts
852 1) a hacker goes to vulnerable WebApp and gets a real sessionid,
853 just by browsing anonymous part of WebApp
854 2) the hacker inserts (somehow) this values into a cookie in victim's browser
855 3) after the victim logs into WebApp the hacker can enter his/her session
857 you should call change_session_id in your login controller like this:
859 if ($c->authenticate( { username => $user, password => $pass } )) {
861 $c->change_session_id;
868 =item change_session_expires $expires
870 You can change the session expiration time for this session;
872 $c->change_session_expires( 4000 );
874 Note that this only works to set the session longer than the config setting.
878 =head1 INTERNAL METHODS
884 This method is extended to also make calls to
885 C<check_session_plugin_requirements> and C<setup_session>.
887 =item check_session_plugin_requirements
889 This method ensures that a State and a Store plugin are also in use by the
894 This method populates C<< $c->config('Plugin::Session') >> with the default values
895 listed in L</CONFIGURATION>.
899 This method is extended.
901 Its only effect is if the (off by default) C<flash_to_stash> configuration
902 parameter is on - then it will copy the contents of the flash to the stash at
905 =item finalize_headers
907 This method is extended and will extend the expiry time before sending
912 This method is extended and will call finalize_session before the other
913 finalize_body methods run. Here we persist the session data if a session exists.
915 =item initialize_session_data
917 This method will initialize the internal structure of the session, and is
918 called by the C<session> method if appropriate.
920 =item create_session_id
922 Creates a new session ID using C<generate_session_id> if there is no session ID
925 =item validate_session_id SID
927 Make sure a session ID is of the right format.
929 This currently ensures that the session ID string is any amount of case
930 insensitive hexadecimal characters.
932 =item generate_session_id
934 This method will return a string that can be used as a session ID. It is
935 supposed to be a reasonably random string with enough bits to prevent
936 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
937 MD5 or SHA-256, depending on the availability of these modules.
939 =item session_hash_seed
941 This method is actually rather internal to generate_session_id, but should be
942 overridable in case you want to provide more random data.
944 Currently it returns a concatenated string which contains:
950 =item * The current time
952 =item * One value from C<rand>.
954 =item * The stringified value of a newly allocated hash reference
956 =item * The stringified value of the Catalyst context object
960 in the hopes that those combined values are entropic enough for most uses. If
961 this is not the case you can replace C<session_hash_seed> with e.g.
963 sub session_hash_seed {
964 open my $fh, "<", "/dev/random";
965 read $fh, my $bytes, 20;
970 Or even more directly, replace C<generate_session_id>:
972 sub generate_session_id {
973 open my $fh, "<", "/dev/random";
974 read $fh, my $bytes, 20;
976 return unpack("H*", $bytes);
979 Also have a look at L<Crypt::Random> and the various openssl bindings - these
980 modules provide APIs for cryptographically secure random data.
982 =item finalize_session
984 Clean up the session during C<finalize>.
986 This clears the various accessors after saving to the store.
990 See L<Catalyst/dump_these> - ammends the session data structure to the list of
991 dumped objects if session ID is defined.
994 =item calculate_extended_session_expires
996 =item calculate_initial_session_expires
998 =item create_session_id_if_needed
1000 =item delete_session_id
1002 =item extend_session_expires
1004 Note: this is *not* used to give an individual user a longer session. See
1005 'change_session_expires'.
1007 =item extend_session_id
1009 =item get_session_id
1011 =item reset_session_expires
1013 =item session_is_valid
1015 =item set_session_id
1017 =item initial_session_expires
1021 =head1 USING SESSIONS DURING PREPARE
1023 The earliest point in time at which you may use the session data is after
1024 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
1026 State plugins must set $c->session ID before C<prepare_action>, and during
1027 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
1030 sub prepare_action {
1033 # don't touch $c->session yet!
1035 $c->NEXT::prepare_action( @_ );
1037 $c->session; # this is OK
1038 $c->sessionid; # this is also OK
1041 =head1 CONFIGURATION
1043 $c->config('Plugin::Session' => {
1047 All configuation parameters are provided in a hash reference under the
1048 C<Plugin::Session> key in the configuration hash.
1054 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
1057 =item expiry_threshold
1059 The time (in seconds) before the session expiration to update the
1060 expiration time (and thus the session).
1062 The purpose of this is to keep the session store from being updated
1063 when nothing else in the session is updated.
1065 Defaults to 0 (in which case, the expiration will always be updated).
1067 =item verify_address
1069 When true, C<< $c->request->address >> will be checked at prepare time. If it is
1070 not the same as the address that initiated the session, the session is deleted.
1074 =item verify_user_agent
1076 When true, C<< $c->request->user_agent >> will be checked at prepare time. If it
1077 is not the same as the user agent that initiated the session, the session is
1082 =item flash_to_stash
1084 This option makes it easier to have actions behave the same whether they were
1085 forwarded to or redirected to. On prepare time it copies the contents of
1086 C<flash> (if any) to the stash.
1092 The hash reference returned by C<< $c->session >> contains several keys which
1093 are automatically set:
1099 This key no longer exists. Use C<session_expires> instead.
1103 The last time a session was saved to the store.
1107 The time when the session was first created.
1111 The value of C<< $c->request->address >> at the time the session was created.
1112 This value is only populated if C<verify_address> is true in the configuration.
1116 The value of C<< $c->request->user_agent >> at the time the session was created.
1117 This value is only populated if C<verify_user_agent> is true in the configuration.
1123 =head2 Round the Robin Proxies
1125 C<verify_address> could make your site inaccessible to users who are behind
1126 load balanced proxies. Some ISPs may give a different IP to each request by the
1127 same client due to this type of proxying. If addresses are verified these
1128 users' sessions cannot persist.
1130 To let these users access your site you can either disable address verification
1131 as a whole, or provide a checkbox in the login dialog that tells the server
1132 that it's OK for the address of the client to change. When the server sees that
1133 this box is checked it should delete the C<__address> special key from the
1134 session hash when the hash is first created.
1136 =head2 Race Conditions
1138 In this day and age where cleaning detergents and Dutch football (not the
1139 American kind) teams roam the plains in great numbers, requests may happen
1140 simultaneously. This means that there is some risk of session data being
1141 overwritten, like this:
1147 request a starts, request b starts, with the same session ID
1151 session data is loaded in request a
1155 session data is loaded in request b
1159 session data is changed in request a
1163 request a finishes, session data is updated and written to store
1167 request b finishes, session data is updated and written to store, overwriting
1168 changes by request a
1172 For applications where any given user's session is only making one request
1173 at a time this plugin should be safe enough.
1181 Yuval Kogman, C<nothingmuch@woobling.org>
1185 Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)
1191 Florian Ragwitz (rafl) C<rafl@debian.org>
1193 Kent Fredric (kentnl)
1195 And countless other contributers from #catalyst. Thanks guys!
1199 Devin Austin (dhoss) <dhoss@cpan.org>
1201 =head1 COPYRIGHT & LICENSE
1203 Copyright (c) 2005 the aforementioned authors. All rights
1204 reserved. This program is free software; you can redistribute
1205 it and/or modify it under the same terms as Perl itself.