3 package Catalyst::Plugin::Session;
4 use base qw/Class::Accessor::Fast/;
10 use Catalyst::Exception ();
13 use Object::Signature ();
16 our $VERSION = "0.18";
18 my @session_data_accessors; # used in delete_session
20 __PACKAGE__->mk_accessors(
21 "_session_delete_reason",
22 @session_data_accessors = qw/
26 _extended_session_expires
31 _tried_loading_session_id
32 _tried_loading_session_data
33 _tried_loading_session_expires
34 _tried_loading_flash_data
44 $c->check_session_plugin_requirements;
50 sub check_session_plugin_requirements {
53 unless ( $c->isa("Catalyst::Plugin::Session::State")
54 && $c->isa("Catalyst::Plugin::Session::Store") )
57 ( "The Session plugin requires both Session::State "
58 . "and Session::Store plugins to be used as well." );
61 Catalyst::Exception->throw($err);
68 my $cfg = ( $c->config->{session} ||= {} );
76 $c->NEXT::setup_session();
82 if ( $c->config->{session}{flash_to_stash}
84 and my $flash_data = $c->flash )
86 @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
89 $c->NEXT::prepare_action(@_);
92 sub finalize_headers {
95 # fix cookie before we send headers
96 $c->_save_session_expires;
98 return $c->NEXT::finalize_headers(@_);
103 my $ret = $c->NEXT::finalize(@_);
105 # then finish the rest
106 $c->finalize_session;
110 sub finalize_session {
113 $c->NEXT::finalize_session;
115 $c->_save_session_id;
119 $c->_clear_session_instance_data;
122 sub _save_session_id {
125 # we already called set when allocating
126 # no need to tell the state plugins anything new
129 sub _save_session_expires {
132 if ( defined($c->_session_expires) ) {
133 my $expires = $c->session_expires; # force extension
135 my $sid = $c->sessionid;
136 $c->store_session_data( "expires:$sid" => $expires );
143 if ( my $session_data = $c->_session ) {
145 no warnings 'uninitialized';
146 if ( Object::Signature::signature($session_data) ne
147 $c->_session_data_sig )
149 $session_data->{__updated} = time();
150 my $sid = $c->sessionid;
151 $c->store_session_data( "session:$sid" => $session_data );
159 if ( my $flash_data = $c->_flash ) {
161 my $hashes = $c->_flash_key_hashes || {};
162 my $keep = $c->_flash_keep_keys || {};
163 foreach my $key ( keys %$hashes ) {
164 if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
165 delete $flash_data->{$key};
169 my $sid = $c->sessionid;
172 $c->store_session_data( "flash:$sid", $flash_data );
175 $c->delete_session_data("flash:$sid");
180 sub _load_session_expires {
182 return $c->_session_expires if $c->_tried_loading_session_expires;
183 $c->_tried_loading_session_expires(1);
185 if ( my $sid = $c->sessionid ) {
186 my $expires = $c->get_session_data("expires:$sid") || 0;
188 if ( $expires >= time() ) {
189 $c->_session_expires( $expires );
192 $c->delete_session( "session expired" );
202 return $c->_session if $c->_tried_loading_session_data;
203 $c->_tried_loading_session_data(1);
205 if ( my $sid = $c->sessionid ) {
206 if ( $c->_load_session_expires ) { # > 0
208 my $session_data = $c->get_session_data("session:$sid") || return;
209 $c->_session($session_data);
211 no warnings 'uninitialized'; # ne __address
212 if ( $c->config->{session}{verify_address}
213 && $session_data->{__address} ne $c->request->address )
216 "Deleting session $sid due to address mismatch ("
217 . $session_data->{__address} . " != "
218 . $c->request->address . ")"
220 $c->delete_session("address mismatch");
224 $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
225 $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
226 $c->_expire_session_keys;
228 return $session_data;
237 return $c->_flash if $c->_tried_loading_flash_data;
238 $c->_tried_loading_flash_data(1);
240 if ( my $sid = $c->sessionid ) {
241 if ( my $flash_data = $c->_flash
242 || $c->_flash( $c->get_session_data("flash:$sid") ) )
244 $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
253 sub _expire_session_keys {
254 my ( $c, $data ) = @_;
258 my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
259 foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
260 delete $c->_session->{$key};
261 delete $expire_times->{$key};
265 sub _clear_session_instance_data {
267 $c->$_(undef) for @session_data_accessors;
268 $c->NEXT::_clear_session_instance_data; # allow other plugins to hook in on this
272 my ( $c, $msg ) = @_;
274 $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
276 # delete the session data
277 if ( my $sid = $c->sessionid ) {
278 $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
279 $c->delete_session_id($sid);
282 # reset the values in the context object
283 # see the BEGIN block
284 $c->_clear_session_instance_data;
286 $c->_session_delete_reason($msg);
289 sub session_delete_reason {
292 $c->session_is_valid; # check that it was loaded
294 $c->_session_delete_reason(@_);
297 sub session_expires {
300 if ( defined( my $expires = $c->_extended_session_expires ) ) {
302 } elsif ( defined( $expires = $c->_load_session_expires ) ) {
303 return $c->extend_session_expires( $expires );
309 sub extend_session_expires {
310 my ( $c, $expires ) = @_;
311 $c->_extended_session_expires( my $updated = $c->calculate_extended_session_expires( $expires ) );
312 $c->extend_session_id( $c->sessionid, $updated );
316 sub calculate_initial_session_expires {
318 return ( time() + $c->config->{session}{expires} );
321 sub calculate_extended_session_expires {
322 my ( $c, $prev ) = @_;
323 $c->calculate_initial_session_expires;
326 sub reset_session_expires {
327 my ( $c, $sid ) = @_;
329 my $exp = $c->calculate_initial_session_expires;
330 $c->_session_expires( $exp );
331 $c->_extended_session_expires( $exp );
338 return $c->_sessionid || $c->_load_sessionid;
341 sub _load_sessionid {
343 return if $c->_tried_loading_session_id;
344 $c->_tried_loading_session_id(1);
346 if ( defined( my $sid = $c->get_session_id ) ) {
347 if ( $c->validate_session_id($sid) ) {
348 # temporarily set the inner key, so that validation will work
349 $c->_sessionid($sid);
352 my $err = "Tried to set invalid session ID '$sid'";
353 $c->log->error($err);
354 Catalyst::Exception->throw($err);
361 sub session_is_valid {
364 # force a check for expiry, but also __address, etc
365 if ( $c->_load_session ) {
372 sub validate_session_id {
373 my ( $c, $sid ) = @_;
375 $sid and $sid =~ /^[a-f\d]+$/i;
381 $c->_session || $c->_load_session || do {
382 $c->create_session_id_if_needed;
383 $c->initialize_session_data;
388 my ( $c, @keys ) = @_;
389 my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
390 (@{$href}{@keys}) = ((undef) x @keys);
395 $c->_flash || $c->_load_flash || do {
396 $c->create_session_id_if_needed;
404 my $items = @_ > 1 ? {@_} : $_[0];
405 croak('flash takes a hash or hashref') unless ref $items;
406 @{ $c->_flash }{ keys %$items } = values %$items;
420 #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
421 $c->_flash_key_hashes({});
422 $c->_flash_keep_keys({});
426 sub session_expire_key {
427 my ( $c, %keys ) = @_;
430 @{ $c->session->{__expire_keys} }{ keys %keys } =
431 map { $now + $_ } values %keys;
434 sub initialize_session_data {
445 $c->config->{session}{verify_address}
446 ? ( __address => $c->request->address )
453 sub generate_session_id {
456 my $digest = $c->_find_digest();
457 $digest->add( $c->session_hash_seed() );
458 return $digest->hexdigest;
461 sub create_session_id_if_needed {
463 $c->create_session_id unless $c->sessionid;
466 sub create_session_id {
469 my $sid = $c->generate_session_id;
471 $c->log->debug(qq/Created session "$sid"/) if $c->debug;
473 $c->_sessionid($sid);
474 $c->reset_session_expires;
475 $c->set_session_id($sid);
482 sub session_hash_seed {
485 return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
490 sub _find_digest () {
492 foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
493 if ( eval { Digest->new($alg) } ) {
498 Catalyst::Exception->throw(
499 "Could not find a suitable Digest module. Please install "
500 . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
504 return Digest->new($usable);
511 $c->NEXT::dump_these(),
514 ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
520 sub get_session_id { shift->NEXT::get_session_id(@_) }
521 sub set_session_id { shift->NEXT::set_session_id(@_) }
522 sub delete_session_id { shift->NEXT::delete_session_id(@_) }
523 sub extend_session_id { shift->NEXT::extend_session_id(@_) }
533 Catalyst::Plugin::Session - Generic Session plugin - ties together server side
534 storage and client side state required to maintain session data.
538 # To get sessions to "just work", all you need to do is use these plugins:
542 Session::Store::FastMmap
543 Session::State::Cookie
546 # you can replace Store::FastMmap with Store::File - both have sensible
547 # default configurations (see their docs for details)
549 # more complicated backends are available for other scenarios (DBI storage,
553 # after you've loaded the plugins you can save session data
554 # For example, if you are writing a shopping cart, it could be implemented
557 sub add_item : Local {
558 my ( $self, $c ) = @_;
560 my $item_id = $c->req->param("item");
562 # $c->session is a hash ref, a bit like $c->stash
563 # the difference is that it' preserved across requests
565 push @{ $c->session->{items} }, $item_id;
567 $c->forward("MyView");
570 sub display_items : Local {
571 my ( $self, $c ) = @_;
573 # values in $c->session are restored
574 $c->stash->{items_to_display} =
575 [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
577 $c->forward("MyView");
582 The Session plugin is the base of two related parts of functionality required
583 for session management in web applications.
585 The first part, the State, is getting the browser to repeat back a session key,
586 so that the web application can identify the client and logically string
587 several requests together into a session.
589 The second part, the Store, deals with the actual storage of information about
590 the client. This data is stored so that the it may be revived for every request
591 made by the same client.
593 This plugin links the two pieces together.
595 =head1 RECOMENDED BACKENDS
599 =item Session::State::Cookie
601 The only really sane way to do state is using cookies.
603 =item Session::Store::File
605 A portable backend, based on Cache::File.
607 =item Session::Store::FastMmap
609 A fast and flexible backend, based on Cache::FastMmap.
619 An accessor for the session ID value.
623 Returns a hash reference that might contain unserialized values from previous
624 requests in the same session, and whose modified value will be saved for future
627 This method will automatically create a new session and session ID if none
630 =item session_expires
632 =item session_expires $reset
634 This method returns the time when the current session will expire, or 0 if
635 there is no current session. If there is a session and it already expired, it
636 will delete the session and return 0 as well.
638 If the C<$reset> parameter is true, and there is a session ID the expiry time
639 will be reset to the current time plus the time to live (see
640 L</CONFIGURATION>). This is used when creating a new session.
644 This is like Ruby on Rails' flash data structure. Think of it as a stash that
645 lasts for longer than one request, letting you redirect instead of forward.
647 The flash data will be cleaned up only on requests on which actually use
648 $c->flash (thus allowing multiple redirections), and the policy is to delete
649 all the keys which haven't changed since the flash data was loaded at the end
653 my ( $self, $c ) = @_;
655 $c->flash->{beans} = 10;
656 $c->response->redirect( $c->uri_for("foo") );
660 my ( $self, $c ) = @_;
662 my $value = $c->flash->{beans};
666 $c->response->redirect( $c->uri_for("bar") );
670 my ( $self, $c ) = @_;
672 if ( exists $c->flash->{beans} ) { # false
679 Zap all the keys in the flash regardless of their current state.
681 =item keep_flash @keys
683 If you wawnt to keep a flash key for the next request too, even if it hasn't
684 changed, call C<keep_flash> and pass in the keys as arguments.
686 =item delete_session REASON
688 This method is used to invalidate a session. It takes an optional parameter
689 which will be saved in C<session_delete_reason> if provided.
691 =item session_delete_reason
693 This accessor contains a string with the reason a session was deleted. Possible
708 =item session_expire_key $key, $ttl
710 Mark a key to expire at a certain time (only useful when shorter than the
711 expiry time for the whole session).
715 __PACKAGE__->config->{session}{expires} = 1000000000000; # forever
719 $c->session_expire_key( __user => 3600 );
721 Will make the session data survive, but the user will still be logged out after
724 Note that these values are not auto extended.
728 =head1 INTERNAL METHODS
734 This method is extended to also make calls to
735 C<check_session_plugin_requirements> and C<setup_session>.
737 =item check_session_plugin_requirements
739 This method ensures that a State and a Store plugin are also in use by the
744 This method populates C<< $c->config->{session} >> with the default values
745 listed in L</CONFIGURATION>.
749 This methoid is extended.
751 It's only effect is if the (off by default) C<flash_to_stash> configuration
752 parameter is on - then it will copy the contents of the flash to the stash at
755 =item finalize_headers
757 This method is extended and will extend the expiry time before sending
762 This method is extended and will call finalize_session after the other
763 finalizes run. Here we persist the session data if a session exists.
765 =item initialize_session_data
767 This method will initialize the internal structure of the session, and is
768 called by the C<session> method if appropriate.
770 =item create_session_id
772 Creates a new session id using C<generate_session_id> if there is no session ID
775 =item validate_session_id SID
777 Make sure a session ID is of the right format.
779 This currently ensures that the session ID string is any amount of case
780 insensitive hexadecimal characters.
782 =item generate_session_id
784 This method will return a string that can be used as a session ID. It is
785 supposed to be a reasonably random string with enough bits to prevent
786 collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
787 MD5 or SHA-256, depending on the availibility of these modules.
789 =item session_hash_seed
791 This method is actually rather internal to generate_session_id, but should be
792 overridable in case you want to provide more random data.
794 Currently it returns a concatenated string which contains:
808 One value from C<rand>.
812 The stringified value of a newly allocated hash reference
816 The stringified value of the Catalyst context object
820 In the hopes that those combined values are entropic enough for most uses. If
821 this is not the case you can replace C<session_hash_seed> with e.g.
823 sub session_hash_seed {
824 open my $fh, "<", "/dev/random";
825 read $fh, my $bytes, 20;
830 Or even more directly, replace C<generate_session_id>:
832 sub generate_session_id {
833 open my $fh, "<", "/dev/random";
834 read $fh, my $bytes, 20;
836 return unpack("H*", $bytes);
839 Also have a look at L<Crypt::Random> and the various openssl bindings - these
840 modules provide APIs for cryptographically secure random data.
842 =item finalize_session
844 Clean up the session during C<finalize>.
846 This clears the various accessors after saving to the store.
850 See L<Catalyst/dump_these> - ammends the session data structure to the list of
851 dumped objects if session ID is defined.
854 =item calculate_extended_session_expires
856 =item calculate_initial_session_expires
858 =item create_session_id_if_needed
860 =item delete_session_id
862 =item extend_session_expires
864 =item extend_session_id
868 =item reset_session_expires
870 =item session_is_valid
876 =head1 USING SESSIONS DURING PREPARE
878 The earliest point in time at which you may use the session data is after
879 L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
881 State plugins must set $c->session ID before C<prepare_action>, and during
882 C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
888 # don't touch $c->session yet!
890 $c->NEXT::prepare_action( @_ );
892 $c->session; # this is OK
893 $c->sessionid; # this is also OK
898 $c->config->{session} = {
902 All configuation parameters are provided in a hash reference under the
903 C<session> key in the configuration hash.
909 The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
914 When true, C<<$c->request->address>> will be checked at prepare time. If it is
915 not the same as the address that initiated the session, the session is deleted.
921 This option makes it easier to have actions behave the same whether they were
922 forwarded to or redirected to. On prepare time it copies the contents of
923 C<flash> (if any) to the stash.
929 The hash reference returned by C<< $c->session >> contains several keys which
930 are automatically set:
936 This key no longer exists. Use C<session_expires> instead.
940 The last time a session was saved to the store.
944 The time when the session was first created.
948 The value of C<< $c->request->address >> at the time the session was created.
949 This value is only populated if C<verify_address> is true in the configuration.
955 =head2 Round the Robin Proxies
957 C<verify_address> could make your site inaccessible to users who are behind
958 load balanced proxies. Some ISPs may give a different IP to each request by the
959 same client due to this type of proxying. If addresses are verified these
960 users' sessions cannot persist.
962 To let these users access your site you can either disable address verification
963 as a whole, or provide a checkbox in the login dialog that tells the server
964 that it's OK for the address of the client to change. When the server sees that
965 this box is checked it should delete the C<__address> sepcial key from the
966 session hash when the hash is first created.
968 =head2 Race Conditions
970 In this day and age where cleaning detergents and dutch football (not the
971 american kind) teams roam the plains in great numbers, requests may happen
972 simultaneously. This means that there is some risk of session data being
973 overwritten, like this:
979 request a starts, request b starts, with the same session id
983 session data is loaded in request a
987 session data is loaded in request b
991 session data is changed in request a
995 request a finishes, session data is updated and written to store
999 request b finishes, session data is updated and written to store, overwriting
1000 changes by request a
1004 If this is a concern in your application, a soon to be developed locking
1005 solution is the only safe way to go. This will have a bigger overhead.
1007 For applications where any given user is only making one request at a time this
1008 plugin should be safe enough.
1016 =item Christian Hansen
1018 =item Yuval Kogman, C<nothingmuch@woobling.org> (current maintainer)
1020 =item Sebastian Riedel
1024 And countless other contributers from #catalyst. Thanks guys!
1026 =head1 COPYRIGHT & LICENSE
1028 Copyright (c) 2005 the aforementioned authors. All rights
1029 reserved. This program is free software; you can redistribute
1030 it and/or modify it under the same terms as Perl itself.