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.26';
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
38 sub _session_plugin_config {
40 # FIXME - Start warning once all the state/store modules have also been updated.
41 #$c->log->warn("Deprecated 'session' config key used, please use the key 'Plugin::Session' instead")
42 # if exists $c->config->{session}
43 #$c->config->{'Plugin::Session'} ||= delete($c->config->{session}) || {};
44 $c->config->{'Plugin::Session'} ||= $c->config->{session} || {};
50 $c->maybe::next::method(@_);
52 $c->check_session_plugin_requirements;
58 sub check_session_plugin_requirements {
61 unless ( $c->isa("Catalyst::Plugin::Session::State")
62 && $c->isa("Catalyst::Plugin::Session::Store") )
65 ( "The Session plugin requires both Session::State "
66 . "and Session::Store plugins to be used as well." );
69 Catalyst::Exception->throw($err);
76 my $cfg = $c->_session_plugin_config;
81 verify_user_agent => 0,
85 $c->maybe::next::method();
91 $c->maybe::next::method(@_);
93 if ( $c->_session_plugin_config->{flash_to_stash}
95 and my $flash_data = $c->flash )
97 @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
101 sub finalize_headers {
104 # fix cookie before we send headers
105 $c->_save_session_expires;
107 return $c->maybe::next::method(@_);
113 # We have to finalize our session *before* $c->engine->finalize_xxx is called,
114 # because we do not want to send the HTTP response before the session is stored/committed to
115 # the session database (or whatever Session::Store you use).
116 $c->finalize_session;
118 return $c->maybe::next::method(@_);
121 sub finalize_session {
124 $c->maybe::next::method(@_);
126 $c->_save_session_id;
130 $c->_clear_session_instance_data;
133 sub _save_session_id {
136 # we already called set when allocating
137 # no need to tell the state plugins anything new
140 sub _save_session_expires {
143 if ( defined($c->_session_expires) ) {
144 my $expires = $c->session_expires; # force extension
146 my $sid = $c->sessionid;
147 $c->store_session_data( "expires:$sid" => $expires );
154 if ( my $session_data = $c->_session ) {
156 no warnings 'uninitialized';
157 if ( Object::Signature::signature($session_data) ne
158 $c->_session_data_sig )
160 $session_data->{__updated} = time();
161 my $sid = $c->sessionid;
162 $c->store_session_data( "session:$sid" => $session_data );
170 if ( my $flash_data = $c->_flash ) {
172 my $hashes = $c->_flash_key_hashes || {};
173 my $keep = $c->_flash_keep_keys || {};
174 foreach my $key ( keys %$hashes ) {
175 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
176 delete $flash_data->{$key};
180 my $sid = $c->sessionid;
182 my $session_data = $c->_session;
184 $session_data->{__flash} = $flash_data;
187 delete $session_data->{__flash};
189 $c->_session($session_data);
194 sub _load_session_expires {
196 return $c->_session_expires if $c->_tried_loading_session_expires;
197 $c->_tried_loading_session_expires(1);
199 if ( my $sid = $c->sessionid ) {
200 my $expires = $c->get_session_data("expires:$sid") || 0;
202 if ( $expires >= time() ) {
203 $c->_session_expires( $expires );
206 $c->delete_session( "session expired" );
216 return $c->_session if $c->_tried_loading_session_data;
217 $c->_tried_loading_session_data(1);
219 if ( my $sid = $c->sessionid ) {
220 if ( $c->_load_session_expires ) { # > 0
222 my $session_data = $c->get_session_data("session:$sid") || return;
223 $c->_session($session_data);
225 no warnings 'uninitialized'; # ne __address
226 if ( $c->_session_plugin_config->{verify_address}
227 && $session_data->{__address} ne $c->request->address )
230 "Deleting session $sid due to address mismatch ("
231 . $session_data->{__address} . " != "
232 . $c->request->address . ")"
234 $c->delete_session("address mismatch");
237 if ( $c->_session_plugin_config->{verify_user_agent}
238 && $session_data->{__user_agent} ne $c->request->user_agent )
241 "Deleting session $sid due to user agent mismatch ("
242 . $session_data->{__user_agent} . " != "
243 . $c->request->user_agent . ")"
245 $c->delete_session("user agent mismatch");
249 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
250 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
251 $c->_expire_session_keys;
253 return $session_data;
262 return $c->_flash if $c->_tried_loading_flash_data;
263 $c->_tried_loading_flash_data(1);
265 if ( my $sid = $c->sessionid ) {
267 my $session_data = $c->session;
268 $c->_flash($session_data->{__flash});
270 if ( my $flash_data = $c->_flash )
272 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
281 sub _expire_session_keys {
282 my ( $c, $data ) = @_;
286 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
287 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
288 delete $c->_session->{$key};
289 delete $expire_times->{$key};
293 sub _clear_session_instance_data {
295 $c->$_(undef) for @session_data_accessors;
296 $c->maybe::next::method(@_); # allow other plugins to hook in on this
299 sub change_session_id {
302 my $sessiondata = $c->session;
303 my $oldsid = $c->sessionid;
304 my $newsid = $c->create_session_id;
307 $c->log->debug(qq/change_sessid: deleting session data from "$oldsid"/) if $c->debug;
308 $c->delete_session_data("${_}:${oldsid}") for qw/session expires flash/;
311 $c->log->debug(qq/change_sessid: storing session data to "$newsid"/) if $c->debug;
312 $c->store_session_data( "session:$newsid" => $sessiondata );
318 my ( $c, $msg ) = @_;
320 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
322 # delete the session data
323 if ( my $sid = $c->sessionid ) {
324 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
325 $c->delete_session_id($sid);
328 # reset the values in the context object
329 # see the BEGIN block
330 $c->_clear_session_instance_data;
332 $c->_session_delete_reason($msg);
335 sub session_delete_reason {
338 $c->session_is_valid; # check that it was loaded
340 $c->_session_delete_reason(@_);
343 sub session_expires {
346 if ( defined( my $expires = $c->_extended_session_expires ) ) {
348 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
349 return $c->extend_session_expires( $expires );
355 sub extend_session_expires {
356 my ( $c, $expires ) = @_;
357 $c->_extended_session_expires( my $updated = $c->calculate_extended_session_expires( $expires ) );
358 $c->extend_session_id( $c->sessionid, $updated );
362 sub calculate_initial_session_expires {
364 return ( time() + $c->_session_plugin_config->{expires} );
367 sub calculate_extended_session_expires {
368 my ( $c, $prev ) = @_;
369 $c->calculate_initial_session_expires;
372 sub reset_session_expires {
373 my ( $c, $sid ) = @_;
375 my $exp = $c->calculate_initial_session_expires;
376 $c->_session_expires( $exp );
377 $c->_extended_session_expires( $exp );
384 return $c->_sessionid || $c->_load_sessionid;
387 sub _load_sessionid {
389 return if $c->_tried_loading_session_id;
390 $c->_tried_loading_session_id(1);
392 if ( defined( my $sid = $c->get_session_id ) ) {
393 if ( $c->validate_session_id($sid) ) {
394 # temporarily set the inner key, so that validation will work
395 $c->_sessionid($sid);
398 my $err = "Tried to set invalid session ID '$sid'";
399 $c->log->error($err);
400 Catalyst::Exception->throw($err);
407 sub session_is_valid {
410 # force a check for expiry, but also __address, etc
411 if ( $c->_load_session ) {
418 sub validate_session_id {
419 my ( $c, $sid ) = @_;
421 $sid and $sid =~ /^[a-f\d]+$/i;
427 $c->_session || $c->_load_session || do {
428 $c->create_session_id_if_needed;
429 $c->initialize_session_data;
434 my ( $c, @keys ) = @_;
435 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
436 (@{$href}{@keys}) = ((undef) x @keys);
441 $c->_flash || $c->_load_flash || do {
442 $c->create_session_id_if_needed;
450 my $items = @_ > 1 ? {@_} : $_[0];
451 croak('flash takes a hash or hashref') unless ref $items;
452 @{ $c->_flash }{ keys %$items } = values %$items;
466 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
467 $c->_flash_key_hashes({});
468 $c->_flash_keep_keys({});
472 sub session_expire_key {
473 my ( $c, %keys ) = @_;
476 @{ $c->session->{__expire_keys} }{ keys %keys } =
477 map { $now + $_ } values %keys;
480 sub initialize_session_data {
491 $c->_session_plugin_config->{verify_address}
492 ? ( __address => $c->request->address||'' )
496 $c->_session_plugin_config->{verify_user_agent}
497 ? ( __user_agent => $c->request->user_agent||'' )
504 sub generate_session_id {
507 my $digest = $c->_find_digest();
508 $digest->add( $c->session_hash_seed() );
509 return $digest->hexdigest;
512 sub create_session_id_if_needed {
514 $c->create_session_id unless $c->sessionid;
517 sub create_session_id {
520 my $sid = $c->generate_session_id;
522 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
524 $c->_sessionid($sid);
525 $c->reset_session_expires;
526 $c->set_session_id($sid);
533 sub session_hash_seed {
536 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
541 sub _find_digest () {
543 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
544 if ( eval { Digest->new($alg) } ) {
549 Catalyst::Exception->throw(
550 "Could not find a suitable Digest module. Please install "
551 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
555 return Digest->new($usable);
562 $c->maybe::next::method(),
565 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
571 sub get_session_id { shift->maybe::next::method(@_) }
572 sub set_session_id { shift->maybe::next::method(@_) }
573 sub delete_session_id { shift->maybe::next::method(@_) }
574 sub extend_session_id { shift->maybe::next::method(@_) }
584 Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
588 # To get sessions to "just work", all you need to do is use these plugins:
592 Session::Store::FastMmap
593 Session::State::Cookie
596 # you can replace Store::FastMmap with Store::File - both have sensible
597 # default configurations (see their docs for details)
599 # more complicated backends are available for other scenarios (DBI storage,
603 # after you've loaded the plugins you can save session data
604 # For example, if you are writing a shopping cart, it could be implemented
607 sub add_item : Local {
608 my ( $self, $c ) = @_;
610 my $item_id = $c->req->param("item");
612 # $c->session is a hash ref, a bit like $c->stash
613 # the difference is that it' preserved across requests
615 push @{ $c->session->{items} }, $item_id;
617 $c->forward("MyView");
620 sub display_items : Local {
621 my ( $self, $c ) = @_;
623 # values in $c->session are restored
624 $c->stash->{items_to_display} =
625 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
627 $c->forward("MyView");
632 The Session plugin is the base of two related parts of functionality required
633 for session management in web applications.
635 The first part, the State, is getting the browser to repeat back a session key,
636 so that the web application can identify the client and logically string
637 several requests together into a session.
639 The second part, the Store, deals with the actual storage of information about
640 the client. This data is stored so that the it may be revived for every request
641 made by the same client.
643 This plugin links the two pieces together.
645 =head1 RECOMENDED BACKENDS
649 =item Session::State::Cookie
651 The only really sane way to do state is using cookies.
653 =item Session::Store::File
655 A portable backend, based on Cache::File.
657 =item Session::Store::FastMmap
659 A fast and flexible backend, based on Cache::FastMmap.
669 An accessor for the session ID value.
673 Returns a hash reference that might contain unserialized values from previous
674 requests in the same session, and whose modified value will be saved for future
677 This method will automatically create a new session and session ID if none
680 =item session_expires
682 =item session_expires $reset
684 This method returns the time when the current session will expire, or 0 if
685 there is no current session. If there is a session and it already expired, it
686 will delete the session and return 0 as well.
688 If the C<$reset> parameter is true, and there is a session ID the expiry time
689 will be reset to the current time plus the time to live (see
690 L</CONFIGURATION>). This is used when creating a new session.
694 This is like Ruby on Rails' flash data structure. Think of it as a stash that
695 lasts for longer than one request, letting you redirect instead of forward.
697 The flash data will be cleaned up only on requests on which actually use
698 $c->flash (thus allowing multiple redirections), and the policy is to delete
699 all the keys which haven't changed since the flash data was loaded at the end
703 my ( $self, $c ) = @_;
705 $c->flash->{beans} = 10;
706 $c->response->redirect( $c->uri_for("foo") );
710 my ( $self, $c ) = @_;
712 my $value = $c->flash->{beans};
716 $c->response->redirect( $c->uri_for("bar") );
720 my ( $self, $c ) = @_;
722 if ( exists $c->flash->{beans} ) { # false
729 Zap all the keys in the flash regardless of their current state.
731 =item keep_flash @keys
733 If you want to keep a flash key for the next request too, even if it hasn't
734 changed, call C<keep_flash> and pass in the keys as arguments.
736 =item delete_session REASON
738 This method is used to invalidate a session. It takes an optional parameter
739 which will be saved in C<session_delete_reason> if provided.
741 NOTE: This method will B<also> delete your flash data.
743 =item session_delete_reason
745 This accessor contains a string with the reason a session was deleted. Possible
760 =item session_expire_key $key, $ttl
762 Mark a key to expire at a certain time (only useful when shorter than the
763 expiry time for the whole session).
767 __PACKAGE__->config('Plugin::Session' => { expires => 1000000000000 }); # forever
771 $c->session_expire_key( __user => 3600 );
773 Will make the session data survive, but the user will still be logged out after
776 Note that these values are not auto extended.
778 =item change_session_id
780 By calling this method you can force a session id change while keeping all
781 session data. This method might come handy when you are paranoid about some
782 advanced variations of session fixation attack.
784 If you want to prevent this session fixation scenario:
786 0) let us have WebApp with anonymous and authenticated parts
787 1) a hacker goes to vulnerable WebApp and gets a real sessionid,
788 just by browsing anonymous part of WebApp
789 2) the hacker inserts (somehow) this values into a cookie in victim's browser
790 3) after the victim logs into WebApp the hacker can enter his/her session
792 you should call change_session_id in your login controller like this:
794 if ($c->authenticate( { username => $user, password => $pass } )) {
796 $c->change_session_id;
805 =head1 INTERNAL METHODS
811 This method is extended to also make calls to
812 C<check_session_plugin_requirements> and C<setup_session>.
814 =item check_session_plugin_requirements
816 This method ensures that a State and a Store plugin are also in use by the
821 This method populates C<< $c->config('Plugin::Session') >> with the default values
822 listed in L</CONFIGURATION>.
826 This method is extended.
828 Its only effect is if the (off by default) C<flash_to_stash> configuration
829 parameter is on - then it will copy the contents of the flash to the stash at
832 =item finalize_headers
834 This method is extended and will extend the expiry time before sending
839 This method is extended and will call finalize_session before the other
840 finalize_body methods run. Here we persist the session data if a session exists.
842 =item initialize_session_data
844 This method will initialize the internal structure of the session, and is
845 called by the C<session> method if appropriate.
847 =item create_session_id
849 Creates a new session ID using C<generate_session_id> if there is no session ID
852 =item validate_session_id SID
854 Make sure a session ID is of the right format.
856 This currently ensures that the session ID string is any amount of case
857 insensitive hexadecimal characters.
859 =item generate_session_id
861 This method will return a string that can be used as a session ID. It is
862 supposed to be a reasonably random string with enough bits to prevent
863 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
864 MD5 or SHA-256, depending on the availability of these modules.
866 =item session_hash_seed
868 This method is actually rather internal to generate_session_id, but should be
869 overridable in case you want to provide more random data.
871 Currently it returns a concatenated string which contains:
877 =item * The current time
879 =item * One value from C<rand>.
881 =item * The stringified value of a newly allocated hash reference
883 =item * The stringified value of the Catalyst context object
887 in the hopes that those combined values are entropic enough for most uses. If
888 this is not the case you can replace C<session_hash_seed> with e.g.
890 sub session_hash_seed {
891 open my $fh, "<", "/dev/random";
892 read $fh, my $bytes, 20;
897 Or even more directly, replace C<generate_session_id>:
899 sub generate_session_id {
900 open my $fh, "<", "/dev/random";
901 read $fh, my $bytes, 20;
903 return unpack("H*", $bytes);
906 Also have a look at L<Crypt::Random> and the various openssl bindings - these
907 modules provide APIs for cryptographically secure random data.
909 =item finalize_session
911 Clean up the session during C<finalize>.
913 This clears the various accessors after saving to the store.
917 See L<Catalyst/dump_these> - ammends the session data structure to the list of
918 dumped objects if session ID is defined.
921 =item calculate_extended_session_expires
923 =item calculate_initial_session_expires
925 =item create_session_id_if_needed
927 =item delete_session_id
929 =item extend_session_expires
931 =item extend_session_id
935 =item reset_session_expires
937 =item session_is_valid
943 =head1 USING SESSIONS DURING PREPARE
945 The earliest point in time at which you may use the session data is after
946 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
948 State plugins must set $c->session ID before C<prepare_action>, and during
949 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
955 # don't touch $c->session yet!
957 $c->NEXT::prepare_action( @_ );
959 $c->session; # this is OK
960 $c->sessionid; # this is also OK
965 $c->config('Plugin::Session' => {
969 All configuation parameters are provided in a hash reference under the
970 C<Plugin::Session> key in the configuration hash.
976 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
981 When true, C<<$c->request->address>> will be checked at prepare time. If it is
982 not the same as the address that initiated the session, the session is deleted.
986 =item verify_user_agent
988 When true, C<<$c->request->user_agent>> will be checked at prepare time. If it
989 is not the same as the user agent that initiated the session, the session is
996 This option makes it easier to have actions behave the same whether they were
997 forwarded to or redirected to. On prepare time it copies the contents of
998 C<flash> (if any) to the stash.
1004 The hash reference returned by C<< $c->session >> contains several keys which
1005 are automatically set:
1011 This key no longer exists. Use C<session_expires> instead.
1015 The last time a session was saved to the store.
1019 The time when the session was first created.
1023 The value of C<< $c->request->address >> at the time the session was created.
1024 This value is only populated if C<verify_address> is true in the configuration.
1028 The value of C<< $c->request->user_agent >> at the time the session was created.
1029 This value is only populated if C<verify_user_agent> is true in the configuration.
1035 =head2 Round the Robin Proxies
1037 C<verify_address> could make your site inaccessible to users who are behind
1038 load balanced proxies. Some ISPs may give a different IP to each request by the
1039 same client due to this type of proxying. If addresses are verified these
1040 users' sessions cannot persist.
1042 To let these users access your site you can either disable address verification
1043 as a whole, or provide a checkbox in the login dialog that tells the server
1044 that it's OK for the address of the client to change. When the server sees that
1045 this box is checked it should delete the C<__address> special key from the
1046 session hash when the hash is first created.
1048 =head2 Race Conditions
1050 In this day and age where cleaning detergents and Dutch football (not the
1051 American kind) teams roam the plains in great numbers, requests may happen
1052 simultaneously. This means that there is some risk of session data being
1053 overwritten, like this:
1059 request a starts, request b starts, with the same session ID
1063 session data is loaded in request a
1067 session data is loaded in request b
1071 session data is changed in request a
1075 request a finishes, session data is updated and written to store
1079 request b finishes, session data is updated and written to store, overwriting
1080 changes by request a
1084 If this is a concern in your application, a soon-to-be-developed locking
1085 solution is the only safe way to go. This will have a bigger overhead.
1087 For applications where any given user is only making one request at a time this
1088 plugin should be safe enough.
1096 Yuval Kogman, C<nothingmuch@woobling.org>
1100 Tomas Doran (t0m) C<bobtfish@bobtfish.net> (current maintainer)
1106 And countless other contributers from #catalyst. Thanks guys!
1108 =head1 COPYRIGHT & LICENSE
1110 Copyright (c) 2005 the aforementioned authors. All rights
1111 reserved. This program is free software; you can redistribute
1112 it and/or modify it under the same terms as Perl itself.