3 package Catalyst::Plugin::Session;
6 with 'MooseX::Emulate::Class::Accessor::Fast';
8 use Catalyst::Exception ();
11 use Object::Signature ();
13 use List::Util qw/ max /;
15 use namespace::clean -except => 'meta';
17 our $VERSION = '0.37';
18 $VERSION = eval $VERSION;
20 my @session_data_accessors; # used in delete_session
22 __PACKAGE__->mk_accessors(
23 "_session_delete_reason",
24 @session_data_accessors = qw/
28 _extended_session_expires
33 _tried_loading_session_id
34 _tried_loading_session_data
35 _tried_loading_session_expires
36 _tried_loading_flash_data
40 sub _session_plugin_config {
42 # FIXME - Start warning once all the state/store modules have also been updated.
43 #$c->log->warn("Deprecated 'session' config key used, please use the key 'Plugin::Session' instead")
44 # if exists $c->config->{session}
45 #$c->config->{'Plugin::Session'} ||= delete($c->config->{session}) || {};
46 $c->config->{'Plugin::Session'} ||= $c->config->{session} || {};
52 $c->maybe::next::method(@_);
54 $c->check_session_plugin_requirements;
60 sub check_session_plugin_requirements {
63 unless ( $c->isa("Catalyst::Plugin::Session::State")
64 && $c->isa("Catalyst::Plugin::Session::Store") )
67 ( "The Session plugin requires both Session::State "
68 . "and Session::Store plugins to be used as well." );
71 Catalyst::Exception->throw($err);
78 my $cfg = $c->_session_plugin_config;
83 verify_user_agent => 0,
84 expiry_threshold => 0,
88 $c->maybe::next::method();
94 $c->maybe::next::method(@_);
96 if ( $c->_session_plugin_config->{flash_to_stash}
98 and my $flash_data = $c->flash )
100 @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
104 sub finalize_headers {
107 # fix cookie before we send headers
108 $c->_save_session_expires;
110 # Force extension of session_expires before finalizing headers, so a pos
111 # up to date. First call to session_expires will extend the expiry, subs
112 # just return the previously extended value.
115 return $c->maybe::next::method(@_);
121 # We have to finalize our session *before* $c->engine->finalize_xxx is called,
122 # because we do not want to send the HTTP response before the session is stored/committed to
123 # the session database (or whatever Session::Store you use).
124 $c->finalize_session;
126 return $c->maybe::next::method(@_);
129 sub finalize_session {
132 $c->maybe::next::method(@_);
134 $c->_save_session_id;
138 $c->_clear_session_instance_data;
141 sub _save_session_id {
144 # we already called set when allocating
145 # no need to tell the state plugins anything new
148 sub _save_session_expires {
151 if ( defined($c->_session_expires) ) {
153 if (my $sid = $c->sessionid) {
155 my $current = $c->_get_stored_session_expires;
156 my $extended = $c->session_expires;
157 if ($extended > $current) {
158 $c->store_session_data( "expires:$sid" => $extended );
168 if ( my $session_data = $c->_session ) {
170 no warnings 'uninitialized';
171 if ( Object::Signature::signature($session_data) ne
172 $c->_session_data_sig )
174 $session_data->{__updated} = time();
175 my $sid = $c->sessionid;
176 $c->store_session_data( "session:$sid" => $session_data );
184 if ( my $flash_data = $c->_flash ) {
186 my $hashes = $c->_flash_key_hashes || {};
187 my $keep = $c->_flash_keep_keys || {};
188 foreach my $key ( keys %$hashes ) {
189 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
190 delete $flash_data->{$key};
194 my $sid = $c->sessionid;
196 my $session_data = $c->_session;
198 $session_data->{__flash} = $flash_data;
201 delete $session_data->{__flash};
203 $c->_session($session_data);
208 sub _load_session_expires {
210 return $c->_session_expires if $c->_tried_loading_session_expires;
211 $c->_tried_loading_session_expires(1);
213 if ( my $sid = $c->sessionid ) {
214 my $expires = $c->_get_stored_session_expires;
216 if ( $expires >= time() ) {
217 $c->_session_expires( $expires );
220 $c->delete_session( "session expired" );
230 return $c->_session if $c->_tried_loading_session_data;
231 $c->_tried_loading_session_data(1);
233 if ( my $sid = $c->sessionid ) {
234 if ( $c->_load_session_expires ) { # > 0
236 my $session_data = $c->get_session_data("session:$sid") || return;
237 $c->_session($session_data);
239 no warnings 'uninitialized'; # ne __address
240 if ( $c->_session_plugin_config->{verify_address}
241 && exists $session_data->{__address}
242 && $session_data->{__address} ne $c->request->address )
245 "Deleting session $sid due to address mismatch ("
246 . $session_data->{__address} . " != "
247 . $c->request->address . ")"
249 $c->delete_session("address mismatch");
252 if ( $c->_session_plugin_config->{verify_user_agent}
253 && $session_data->{__user_agent} ne $c->request->user_agent )
256 "Deleting session $sid due to user agent mismatch ("
257 . $session_data->{__user_agent} . " != "
258 . $c->request->user_agent . ")"
260 $c->delete_session("user agent mismatch");
264 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
265 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
266 $c->_expire_session_keys;
268 return $session_data;
277 return $c->_flash if $c->_tried_loading_flash_data;
278 $c->_tried_loading_flash_data(1);
280 if ( my $sid = $c->sessionid ) {
282 my $session_data = $c->session;
283 $c->_flash($session_data->{__flash});
285 if ( my $flash_data = $c->_flash )
287 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
296 sub _expire_session_keys {
297 my ( $c, $data ) = @_;
301 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
302 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
303 delete $c->_session->{$key};
304 delete $expire_times->{$key};
308 sub _clear_session_instance_data {
310 $c->$_(undef) for @session_data_accessors;
311 $c->maybe::next::method(@_); # allow other plugins to hook in on this
314 sub change_session_id {
317 my $sessiondata = $c->session;
318 my $oldsid = $c->sessionid;
319 my $newsid = $c->create_session_id;
322 $c->log->debug(qq/change_sessid: deleting session data from "$oldsid"/) if $c->debug;
323 $c->delete_session_data("${_}:${oldsid}") for qw/session expires flash/;
326 $c->log->debug(qq/change_sessid: storing session data to "$newsid"/) if $c->debug;
327 $c->store_session_data( "session:$newsid" => $sessiondata );
333 my ( $c, $msg ) = @_;
335 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
337 # delete the session data
338 if ( my $sid = $c->sessionid ) {
339 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
340 $c->delete_session_id($sid);
343 # reset the values in the context object
344 # see the BEGIN block
345 $c->_clear_session_instance_data;
347 $c->_session_delete_reason($msg);
350 sub session_delete_reason {
353 $c->session_is_valid; # check that it was loaded
355 $c->_session_delete_reason(@_);
358 sub session_expires {
361 if ( defined( my $expires = $c->_extended_session_expires ) ) {
363 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
364 return $c->extend_session_expires( $expires );
370 sub extend_session_expires {
371 my ( $c, $expires ) = @_;
373 my $threshold = $c->_session_plugin_config->{expiry_threshold} || 0;
375 if ( my $sid = $c->sessionid ) {
376 my $expires = $c->_get_stored_session_expires;
377 my $cutoff = $expires - $threshold;
379 if (!$threshold || $cutoff <= time) {
381 $c->_extended_session_expires( my $updated = $c->calculate_initial_session_expires() );
382 $c->extend_session_id( $sid, $updated );
400 sub change_session_expires {
401 my ( $c, $expires ) = @_;
404 my $sid = $c->sessionid;
405 my $time_exp = time() + $expires;
406 $c->store_session_data( "expires:$sid" => $time_exp );
409 sub _get_stored_session_expires {
412 if ( my $sid = $c->sessionid ) {
413 return $c->get_session_data("expires:$sid") || 0;
419 sub initial_session_expires {
421 return ( time() + $c->_session_plugin_config->{expires} );
424 sub calculate_initial_session_expires {
426 return max( $c->initial_session_expires, $c->_get_stored_session_expires );
429 sub calculate_extended_session_expires {
430 my ( $c, $prev ) = @_;
431 return ( time() + $prev );
434 sub reset_session_expires {
435 my ( $c, $sid ) = @_;
437 my $exp = $c->calculate_initial_session_expires;
438 $c->_session_expires( $exp );
440 # since we're setting _session_expires directly, make load_session_expires
441 # actually use that value.
443 $c->_tried_loading_session_expires(1);
444 $c->_extended_session_expires( $exp );
451 return $c->_sessionid || $c->_load_sessionid;
454 sub _load_sessionid {
456 return if $c->_tried_loading_session_id;
457 $c->_tried_loading_session_id(1);
459 if ( defined( my $sid = $c->get_session_id ) ) {
460 if ( $c->validate_session_id($sid) ) {
461 # temporarily set the inner key, so that validation will work
462 $c->_sessionid($sid);
465 my $err = "Tried to set invalid session ID '$sid'";
466 $c->log->error($err);
467 Catalyst::Exception->throw($err);
474 sub session_is_valid {
477 # force a check for expiry, but also __address, etc
478 if ( $c->_load_session ) {
485 sub validate_session_id {
486 my ( $c, $sid ) = @_;
488 $sid and $sid =~ /^[a-f\d]+$/i;
494 my $session = $c->_session || $c->_load_session || do {
495 $c->create_session_id_if_needed;
496 $c->initialize_session_data;
500 my $new_values = @_ > 1 ? { @_ } : $_[0];
501 croak('session takes a hash or hashref') unless ref $new_values;
503 for my $key (keys %$new_values) {
504 $session->{$key} = $new_values->{$key};
512 my ( $c, @keys ) = @_;
513 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
514 (@{$href}{@keys}) = ((undef) x @keys);
519 $c->_flash || $c->_load_flash || do {
520 $c->create_session_id_if_needed;
528 my $items = @_ > 1 ? {@_} : $_[0];
529 croak('flash takes a hash or hashref') unless ref $items;
530 @{ $c->_flash }{ keys %$items } = values %$items;
544 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
545 $c->_flash_key_hashes({});
546 $c->_flash_keep_keys({});
550 sub session_expire_key {
551 my ( $c, %keys ) = @_;
554 @{ $c->session->{__expire_keys} }{ keys %keys } =
555 map { $now + $_ } values %keys;
558 sub initialize_session_data {
569 $c->_session_plugin_config->{verify_address}
570 ? ( __address => $c->request->address||'' )
574 $c->_session_plugin_config->{verify_user_agent}
575 ? ( __user_agent => $c->request->user_agent||'' )
582 sub generate_session_id {
585 my $digest = $c->_find_digest();
586 $digest->add( $c->session_hash_seed() );
587 return $digest->hexdigest;
590 sub create_session_id_if_needed {
592 $c->create_session_id unless $c->sessionid;
595 sub create_session_id {
598 my $sid = $c->generate_session_id;
600 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
602 $c->_sessionid($sid);
603 $c->reset_session_expires;
604 $c->set_session_id($sid);
611 sub session_hash_seed {
614 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
619 sub _find_digest () {
621 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
622 if ( eval { Digest->new($alg) } ) {
627 Catalyst::Exception->throw(
628 "Could not find a suitable Digest module. Please install "
629 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
633 return Digest->new($usable);
640 $c->maybe::next::method(),
643 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
649 sub get_session_id { shift->maybe::next::method(@_) }
650 sub set_session_id { shift->maybe::next::method(@_) }
651 sub delete_session_id { shift->maybe::next::method(@_) }
652 sub extend_session_id { shift->maybe::next::method(@_) }
662 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
666 # To get sessions to "just work", all you need to do is use these plugins:
670 Session::Store::FastMmap
671 Session::State::Cookie
674 # you can replace Store::FastMmap with Store::File - both have sensible
675 # default configurations (see their docs for details)
677 # more complicated backends are available for other scenarios (DBI storage,
681 # after you've loaded the plugins you can save session data
682 # For example, if you are writing a shopping cart, it could be implemented
685 sub add_item : Local {
686 my ( $self, $c ) = @_;
688 my $item_id = $c->req->param("item");
690 # $c->session is a hash ref, a bit like $c->stash
691 # the difference is that it' preserved across requests
693 push @{ $c->session->{items} }, $item_id;
695 $c->forward("MyView");
698 sub display_items : Local {
699 my ( $self, $c ) = @_;
701 # values in $c->session are restored
702 $c->stash->{items_to_display} =
703 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
705 $c->forward("MyView");
710 The Session plugin is the base of two related parts of functionality required
711 for session management in web applications.
713 The first part, the State, is getting the browser to repeat back a session key,
714 so that the web application can identify the client and logically string
715 several requests together into a session.
717 The second part, the Store, deals with the actual storage of information about
718 the client. This data is stored so that the it may be revived for every request
719 made by the same client.
721 This plugin links the two pieces together.
723 =head1 RECOMENDED BACKENDS
727 =item Session::State::Cookie
729 The only really sane way to do state is using cookies.
731 =item Session::Store::File
733 A portable backend, based on Cache::File.
735 =item Session::Store::FastMmap
737 A fast and flexible backend, based on Cache::FastMmap.
747 An accessor for the session ID value.
751 Returns a hash reference that might contain unserialized values from previous
752 requests in the same session, and whose modified value will be saved for future
755 This method will automatically create a new session and session ID if none
758 You can also set session keys by passing a list of key/value pairs or a
761 $c->session->{foo} = "bar"; # This works.
762 $c->session(one => 1, two => 2); # And this.
763 $c->session({ answer => 42 }); # And this.
765 =item session_expires
767 This method returns the time when the current session will expire, or 0 if
768 there is no current session. If there is a session and it already expired, it
769 will delete the session and return 0 as well.
773 This is like Ruby on Rails' flash data structure. Think of it as a stash that
774 lasts for longer than one request, letting you redirect instead of forward.
776 The flash data will be cleaned up only on requests on which actually use
777 $c->flash (thus allowing multiple redirections), and the policy is to delete
778 all the keys which haven't changed since the flash data was loaded at the end
781 Note that use of the flash is an easy way to get data across requests, but
782 it's also strongly disrecommended, due it it being inherently plagued with
783 race conditions. This means that it's unlikely to work well if your
784 users have multiple tabs open at once, or if your site does a lot of AJAX
787 L<Catalyst::Plugin::StatusMessage> is the recommended alternative solution,
788 as this doesn't suffer from these issues.
791 my ( $self, $c ) = @_;
793 $c->flash->{beans} = 10;
794 $c->response->redirect( $c->uri_for("foo") );
798 my ( $self, $c ) = @_;
800 my $value = $c->flash->{beans};
804 $c->response->redirect( $c->uri_for("bar") );
808 my ( $self, $c ) = @_;
810 if ( exists $c->flash->{beans} ) { # false
817 Zap all the keys in the flash regardless of their current state.
819 =item keep_flash @keys
821 If you want to keep a flash key for the next request too, even if it hasn't
822 changed, call C<keep_flash> and pass in the keys as arguments.
824 =item delete_session REASON
826 This method is used to invalidate a session. It takes an optional parameter
827 which will be saved in C<session_delete_reason> if provided.
829 NOTE: This method will B<also> delete your flash data.
831 =item session_delete_reason
833 This accessor contains a string with the reason a session was deleted. Possible
848 =item session_expire_key $key, $ttl
850 Mark a key to expire at a certain time (only useful when shorter than the
851 expiry time for the whole session).
855 __PACKAGE__->config('Plugin::Session' => { expires => 10000000000 }); # "forever"
856 (NB If this number is too large, Y2K38 breakage could result.)
860 $c->session_expire_key( __user => 3600 );
862 Will make the session data survive, but the user will still be logged out after
865 Note that these values are not auto extended.
867 =item change_session_id
869 By calling this method you can force a session id change while keeping all
870 session data. This method might come handy when you are paranoid about some
871 advanced variations of session fixation attack.
873 If you want to prevent this session fixation scenario:
875 0) let us have WebApp with anonymous and authenticated parts
876 1) a hacker goes to vulnerable WebApp and gets a real sessionid,
877 just by browsing anonymous part of WebApp
878 2) the hacker inserts (somehow) this values into a cookie in victim's browser
879 3) after the victim logs into WebApp the hacker can enter his/her session
881 you should call change_session_id in your login controller like this:
883 if ($c->authenticate( { username => $user, password => $pass } )) {
885 $c->change_session_id;
892 =item change_session_expires $expires
894 You can change the session expiration time for this session;
896 $c->change_session_expires( 4000 );
898 Note that this only works to set the session longer than the config setting.
902 =head1 INTERNAL METHODS
908 This method is extended to also make calls to
909 C<check_session_plugin_requirements> and C<setup_session>.
911 =item check_session_plugin_requirements
913 This method ensures that a State and a Store plugin are also in use by the
918 This method populates C<< $c->config('Plugin::Session') >> with the default values
919 listed in L</CONFIGURATION>.
923 This method is extended.
925 Its only effect is if the (off by default) C<flash_to_stash> configuration
926 parameter is on - then it will copy the contents of the flash to the stash at
929 =item finalize_headers
931 This method is extended and will extend the expiry time before sending
936 This method is extended and will call finalize_session before the other
937 finalize_body methods run. Here we persist the session data if a session exists.
939 =item initialize_session_data
941 This method will initialize the internal structure of the session, and is
942 called by the C<session> method if appropriate.
944 =item create_session_id
946 Creates a new session ID using C<generate_session_id> if there is no session ID
949 =item validate_session_id SID
951 Make sure a session ID is of the right format.
953 This currently ensures that the session ID string is any amount of case
954 insensitive hexadecimal characters.
956 =item generate_session_id
958 This method will return a string that can be used as a session ID. It is
959 supposed to be a reasonably random string with enough bits to prevent
960 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
961 MD5 or SHA-256, depending on the availability of these modules.
963 =item session_hash_seed
965 This method is actually rather internal to generate_session_id, but should be
966 overridable in case you want to provide more random data.
968 Currently it returns a concatenated string which contains:
974 =item * The current time
976 =item * One value from C<rand>.
978 =item * The stringified value of a newly allocated hash reference
980 =item * The stringified value of the Catalyst context object
984 in the hopes that those combined values are entropic enough for most uses. If
985 this is not the case you can replace C<session_hash_seed> with e.g.
987 sub session_hash_seed {
988 open my $fh, "<", "/dev/random";
989 read $fh, my $bytes, 20;
994 Or even more directly, replace C<generate_session_id>:
996 sub generate_session_id {
997 open my $fh, "<", "/dev/random";
998 read $fh, my $bytes, 20;
1000 return unpack("H*", $bytes);
1003 Also have a look at L<Crypt::Random> and the various openssl bindings - these
1004 modules provide APIs for cryptographically secure random data.
1006 =item finalize_session
1008 Clean up the session during C<finalize>.
1010 This clears the various accessors after saving to the store.
1014 See L<Catalyst/dump_these> - ammends the session data structure to the list of
1015 dumped objects if session ID is defined.
1018 =item calculate_extended_session_expires
1020 =item calculate_initial_session_expires
1022 =item create_session_id_if_needed
1024 =item delete_session_id
1026 =item extend_session_expires
1028 Note: this is *not* used to give an individual user a longer session. See
1029 'change_session_expires'.
1031 =item extend_session_id
1033 =item get_session_id
1035 =item reset_session_expires
1037 =item session_is_valid
1039 =item set_session_id
1041 =item initial_session_expires
1045 =head1 USING SESSIONS DURING PREPARE
1047 The earliest point in time at which you may use the session data is after
1048 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
1050 State plugins must set $c->session ID before C<prepare_action>, and during
1051 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
1054 sub prepare_action {
1057 # don't touch $c->session yet!
1059 $c->NEXT::prepare_action( @_ );
1061 $c->session; # this is OK
1062 $c->sessionid; # this is also OK
1065 =head1 CONFIGURATION
1067 $c->config('Plugin::Session' => {
1071 All configuation parameters are provided in a hash reference under the
1072 C<Plugin::Session> key in the configuration hash.
1078 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
1081 =item expiry_threshold
1083 Only update the session expiry time if it would otherwise expire
1084 within this many seconds from now.
1086 The purpose of this is to keep the session store from being updated
1087 when nothing else in the session is updated.
1089 Defaults to 0 (in which case, the expiration will always be updated).
1091 =item verify_address
1093 When true, C<< $c->request->address >> will be checked at prepare time. If it is
1094 not the same as the address that initiated the session, the session is deleted.
1098 =item verify_user_agent
1100 When true, C<< $c->request->user_agent >> will be checked at prepare time. If it
1101 is not the same as the user agent that initiated the session, the session is
1106 =item flash_to_stash
1108 This option makes it easier to have actions behave the same whether they were
1109 forwarded to or redirected to. On prepare time it copies the contents of
1110 C<flash> (if any) to the stash.
1116 The hash reference returned by C<< $c->session >> contains several keys which
1117 are automatically set:
1123 This key no longer exists. Use C<session_expires> instead.
1127 The last time a session was saved to the store.
1131 The time when the session was first created.
1135 The value of C<< $c->request->address >> at the time the session was created.
1136 This value is only populated if C<verify_address> is true in the configuration.
1140 The value of C<< $c->request->user_agent >> at the time the session was created.
1141 This value is only populated if C<verify_user_agent> is true in the configuration.
1147 =head2 Round the Robin Proxies
1149 C<verify_address> could make your site inaccessible to users who are behind
1150 load balanced proxies. Some ISPs may give a different IP to each request by the
1151 same client due to this type of proxying. If addresses are verified these
1152 users' sessions cannot persist.
1154 To let these users access your site you can either disable address verification
1155 as a whole, or provide a checkbox in the login dialog that tells the server
1156 that it's OK for the address of the client to change. When the server sees that
1157 this box is checked it should delete the C<__address> special key from the
1158 session hash when the hash is first created.
1160 =head2 Race Conditions
1162 In this day and age where cleaning detergents and Dutch football (not the
1163 American kind) teams roam the plains in great numbers, requests may happen
1164 simultaneously. This means that there is some risk of session data being
1165 overwritten, like this:
1171 request a starts, request b starts, with the same session ID
1175 session data is loaded in request a
1179 session data is loaded in request b
1183 session data is changed in request a
1187 request a finishes, session data is updated and written to store
1191 request b finishes, session data is updated and written to store, overwriting
1192 changes by request a
1196 For applications where any given user's session is only making one request
1197 at a time this plugin should be safe enough.
1205 Yuval Kogman, C<nothingmuch@woobling.org>
1209 Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)
1215 Florian Ragwitz (rafl) C<rafl@debian.org>
1217 Kent Fredric (kentnl)
1219 And countless other contributers from #catalyst. Thanks guys!
1223 Devin Austin (dhoss) <dhoss@cpan.org>
1225 Robert Rothenberg <rrwo@cpan.org>
1227 =head1 COPYRIGHT & LICENSE
1229 Copyright (c) 2005 the aforementioned authors. All rights
1230 reserved. This program is free software; you can redistribute
1231 it and/or modify it under the same terms as Perl itself.