[Catalyst-commits] r8828 - in branches/Catalyst-Plugin-Session: .
flash_in_session flash_in_session/lib flash_in_session/lib/Catalyst
flash_in_session/lib/Catalyst/Plugin
flash_in_session/lib/Catalyst/Plugin/Session
flash_in_session/lib/Catalyst/Plugin/Session/Store
flash_in_session/lib/Catalyst/Plugin/Session/Test
flash_in_session/t flash_in_session/t/lib
flash_in_session/t/lib/Catalyst
flash_in_session/t/lib/Catalyst/Plugin
flash_in_session/t/lib/Catalyst/Plugin/Session
ssalvi at dev.catalyst.perl.org
ssalvi at dev.catalyst.perl.org
Thu Dec 11 16:42:22 GMT 2008
Author: ssalvi
Date: 2008-12-11 16:42:21 +0000 (Thu, 11 Dec 2008)
New Revision: 8828
Added:
branches/Catalyst-Plugin-Session/flash_in_session/
branches/Catalyst-Plugin-Session/flash_in_session/Changes
branches/Catalyst-Plugin-Session/flash_in_session/MANIFEST.SKIP
branches/Catalyst-Plugin-Session/flash_in_session/Makefile.PL
branches/Catalyst-Plugin-Session/flash_in_session/TODO
branches/Catalyst-Plugin-Session/flash_in_session/lib/
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session.pm
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/State.pm
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store.pm
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store/
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store/Dummy.pm
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Test/
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Test/Store.pm
branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Tutorial.pod
branches/Catalyst-Plugin-Session/flash_in_session/t/
branches/Catalyst-Plugin-Session/flash_in_session/t/00_basic_sanity.t
branches/Catalyst-Plugin-Session/flash_in_session/t/01_setup.t
branches/Catalyst-Plugin-Session/flash_in_session/t/03_flash.t
branches/Catalyst-Plugin-Session/flash_in_session/t/05_semi_persistent_flash.t
branches/Catalyst-Plugin-Session/flash_in_session/t/06_finalize.t
branches/Catalyst-Plugin-Session/flash_in_session/t/99_pod.t
branches/Catalyst-Plugin-Session/flash_in_session/t/99_podcoverage.t
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/Catalyst/
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/Catalyst/Plugin/
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/Catalyst/Plugin/Session/
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/Catalyst/Plugin/Session/Store/
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/FlashTestApp.pm
branches/Catalyst-Plugin-Session/flash_in_session/t/lib/SessionTestApp.pm
branches/Catalyst-Plugin-Session/flash_in_session/t/live_app.t
Modified:
branches/Catalyst-Plugin-Session/
Log:
r8825 at minifig: sergio | 2008-12-11 10:50:20 -0500
flash data is now stored inside the session
Property changes on: branches/Catalyst-Plugin-Session
___________________________________________________________________
Name: svk:merge
+ dd4bbdde-bd5d-0410-bf86-8d378e22a0ef:/local/Catalyst/branches/Catalyst-Plugin-Session:8825
Property changes on: branches/Catalyst-Plugin-Session/flash_in_session
___________________________________________________________________
Name: svn:ignore
+ Build
_build
blib
Added: branches/Catalyst-Plugin-Session/flash_in_session/Changes
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/Changes (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/Changes 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,92 @@
+Revision history for Perl extension Catalyst::Plugin::Session
+
+0.20 XXX
+ - Switch to Module::install
+ - Flash data is now stored inside the session (key "__flash") to avoid
+ duplicate entry errors caused by simultaneous select/insert/delete of
+ flash rows when using DBI as a Store.
+
+0.19 2007-10-08
+
+0.18 2007-08-15
+ - Fix Apache engine issue (RT #28845)
+
+0.17 2007-07-16
+ - Skip a test if Cookie is not installed (RT #28137)
+
+0.16 2007-07-03
+ - Stupid makefile
+
+0.15 2007-06-24
+ - Fix the bug that caused sessions to expire immediately when another
+ session was deleted previously in the same request cycle
+ - Changed finalize() to redispatch before saving session
+ so other finalize methods still have access to it.
+
+0.14 2007-01-31
+ - Disable verify_address.
+ - update flash to work like session
+
+0.13 2006-10-12
+ - Rerelease with slightly changed test due to a behavior change in
+ Test::MockObject
+ - add `clear_flash`
+ - improve debug logging
+
+0.12 2006-08-26
+ - refactor out a hookable finalize_session method, for plugins
+ - make _clear_session_instance_data call NEXT::, so that plugins can
+ hook on to that too
+
+0.11 2006-08-10
+ - Lazify expiry calculation and store it in a different instance data
+ slot. This provides greater flexibility for implementing hooks like
+ DynamicExpiry the "right" way.
+
+0.10 2006-08-01
+ - Implement a more well defined finalization order for Session stuff.
+ This solves a problem that was introduced by some value cleanups in
+ the 0.06 release.
+
+0.09 2006-07-31
+ - Fix Catalyst::Plugin::Session::Test::Store
+
+0.08 2006-07-31
+ - rerelease because Module::Bane broke the META.yml. HURAAH
+
+0.07 2006-07-30
+ - Make build tool complain loudly on incompatible versions of state
+ plugins.
+
+0.06 2006-07-29
+ - Change State plugin API to be pull oriented
+ - Lazify more correctly (mostly performance improvements)
+ - Don't try to compute digest of hash when there is no hash
+
+0.05 2006-01-01
+ - Un-workaround the Cache::FastMmap (actually Storable) limitation -
+ it's not C::P::Session's business.
+ - add $c->session_expires
+ - refactor guts
+ - improve semantics of session deletion (now deletes flash data too)
+ - improve lazy-load-ness of session data in the light of expiration
+
+0.04 2005-12-28 09:42:00
+ - Work around a limitation in Cache::FastMmap - must store only
+ references, while expiration was an NV.
+
+0.03 2005-12-26 10:22:00
+ - Lazify loading of session data for better performance and less chance
+ of race conditions
+ - support for $c->flash a la Ruby on Rails
+ - Fixed bug in sessionid algorithm detection.
+ - Separate __expires from the session data - we write it every time
+ - Lazify saving of session data for better performance and less chance
+ of race conditions
+
+0.02 2005-11-23 09:40:00
+ - Doc fixes
+ - No more -Engine=Test
+
+0.01 2005-11-14 12:41:00
+ - Initial release.
Added: branches/Catalyst-Plugin-Session/flash_in_session/MANIFEST.SKIP
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/MANIFEST.SKIP (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/MANIFEST.SKIP 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,32 @@
+# Avoid version control files.
+\bRCS\b
+\bCVS\b
+,v$
+\B\.svn\b
+
+# Avoid Makemaker generated and utility files.
+\bMakefile$
+\bblib
+\bMakeMaker-\d
+\bpm_to_blib$
+\bblibdirs$
+^MANIFEST\.SKIP$
+
+# Avoid Module::Build generated and utility files.
+\bBuild$
+\b_build
+
+# Avoid temp and backup files.
+~$
+\.tmp$
+\.old$
+\.bak$
+\#$
+\b\.#
+^..*\.sw[po]$
+
+# prereq tests may fail due to optionals
+99_prereq\.t$
+
+# Module::Bane
+\bBuild.PL$
Added: branches/Catalyst-Plugin-Session/flash_in_session/Makefile.PL
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/Makefile.PL (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/Makefile.PL 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,56 @@
+use inc::Module::Install 0.68;
+
+if ( -e 'MANIFEST.SKIP' ) {
+ system( 'pod2text lib/Catalyst/Plugin/Session.pm > README' );
+}
+
+is_upgrading_needed();
+
+perl_version '5.008';
+
+name 'Catalyst-Plugin-Session';
+all_from 'lib/Catalyst/Plugin/Session.pm';
+
+requires 'Catalyst::Runtime' => '5.7010';
+requires 'Digest';
+requires 'File::Spec';
+requires 'File::Temp';
+requires 'Object::Signature';
+
+# an indirect dep. needs a certain version.
+requires 'Tie::RefHash' => '1.34';
+
+# for Test::Store
+requires 'Test::More';
+
+test_requires 'Test::Deep';
+test_requires 'Test::Exception';
+test_requires 'Test::MockObject' => '1.01';
+
+WriteAll;
+
+sub is_upgrading_needed {
+ my %state = (
+ Cookie => 0.03,
+ URI => 0.02,
+ );
+
+ foreach my $module (keys %state) {
+ if ( eval "require Catalyst::Plugin::Session::State::$module" and
+ ${"Catalyst::Plugin::Session::State::${module}::VERSION"} < $state{$module} ) {
+ warn <<WARN;
+
+********** NOTE **********
+
+Catalyst::Plugin::Session::State::$module must also be updated!
+
+The currently installed version is *not* compatible with this version of
+Catalyst::Plugin::Session!
+
+The updated versions have been added to the prerequisites.
+
+**************************
+WARN
+ }
+ }
+}
Added: branches/Catalyst-Plugin-Session/flash_in_session/TODO
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/TODO (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/TODO 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,13 @@
+* Store::MultiFile
+ - hierarchal directory structure
+ - filesystem based delete_expired_sessions
+ - no locking (update?)
+ - NFS friendly
+* Store::BerkeleyDB
+ - complement FastMmap, but no LRU silliness
+* Catalyst::Plugin::Semaphores
+ - possible drivers
+ - memcached
+ - flock
+ - berkeleydb
+ - fastmmap
Added: branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/State.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/State.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/State.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,59 @@
+#!/usr/bin/perl
+
+package Catalyst::Plugin::Session::State;
+
+use strict;
+use warnings;
+
+__PACKAGE__;
+
+__END__
+
+=pod
+
+=head1 NAME
+
+Catalyst::Plugin::Session::State - Base class for session state
+preservation plugins.
+
+=head1 SYNOPSIS
+
+ package Catalyst::Plugin::Session::State::MyBackend;
+ use base qw/Catalyst::Plugin::Session::State/;
+
+=head1 DESCRIPTION
+
+This class doesn't actually provide any functionality, but when the
+C<Catalyst::Plugin::Session> module sets up it will check to see that
+C<< YourApp->isa("Catalyst::Plugin::Session::State") >>.
+
+When you write a session state plugin you should subclass this module this
+reason only.
+
+=head1 WRITING STATE PLUGINS
+
+To write a session state plugin you usually need to extend two methods:
+
+=over 4
+
+=item prepare_(action|cookies|whatever)
+
+Set C<sessionid> (accessor) at B<prepare> time using data in the request.
+
+Note that this must happen B<before> other C<prepare_action> instances, in
+order to get along with L<Catalyst::Plugin::Session>. Overriding
+C<prepare_cookies> is probably the stablest approach.
+
+=item finalize
+
+Modify the response at to include the session ID if C<sessionid> is defined,
+using whatever scheme you use. For example, set a cookie,
+
+=back
+
+=cut
+
+
+
+
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store/Dummy.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store/Dummy.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store/Dummy.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,66 @@
+#!/usr/bin/perl
+
+package Catalyst::Plugin::Session::Store::Dummy;
+use base qw/Catalyst::Plugin::Session::Store/;
+
+use strict;
+use warnings;
+
+my %store;
+
+sub get_session_data {
+ my ( $c, @keys ) = @_;
+ @store{@keys};
+}
+
+sub store_session_data {
+ my $c = shift;
+ my %data = @_;
+
+ @store{ keys %data } = values %data;
+}
+
+sub delete_session_data {
+ my ( $c, $sid ) = @_;
+ delete $store{$sid};
+}
+
+sub delete_expired_sessions { }
+
+__PACKAGE__;
+
+__END__
+
+=pod
+
+=head1 NAME
+
+Catalyst::Plugin::Session::Store::Dummy - Doesn't really store sessions - useful for tests.
+
+=head1 SYNOPSIS
+
+ use Catalyst qw/Session Session::Store::Dummy/;
+
+=head1 DESCRIPTION
+
+This plugin will "store" data in a hash.
+
+=head1 METHODS
+
+See L<Catalyst::Plugin::Session::Store>.
+
+=over 4
+
+=item get_session_data
+
+=item store_session_data
+
+=item delete_session_data
+
+=item delete_expired_sessions
+
+=back
+
+=cut
+
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Store.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,120 @@
+#!/usr/bin/perl
+
+package Catalyst::Plugin::Session::Store;
+
+use strict;
+use warnings;
+
+__PACKAGE__;
+
+__END__
+
+=pod
+
+=head1 NAME
+
+Catalyst::Plugin::Session::Store - Base class for session storage
+drivers.
+
+=head1 SYNOPSIS
+
+ package Catalyst::Plugin::Session::Store::MyBackend;
+ use base qw/Catalyst::Plugin::Session::Store/;
+
+=head1 DESCRIPTION
+
+This class doesn't actually provide any functionality, but when the
+C<Catalyst::Plugin::Session> module sets up it will check to see that
+C<< YourApp->isa("Catalyst::Plugin::Session::Store") >>. When you write
+a session storage plugin you should subclass this module for this
+reason. This documentation is intended for authors of session storage
+plugins, not for end users.
+
+=head1 WRITING STORE PLUGINS
+
+All session storage plugins need to adhere to the following interface
+specification to work correctly:
+
+=head2 Required Methods
+
+=over 4
+
+=item get_session_data $key
+
+=item store_session_data $key, $data
+
+Retrieve or store session data by key.
+
+C<$data> is currently either a hash reference (for most keys) or an
+integer value (for expires), but all value types should be supported.
+
+Keys are in the format C<prefix:id>, where C<prefix> is C<session>,
+C<expires>, or C<flash>, and C<id> is always the session ID. Plugins
+such as L<Catalyst::Plugin::Session::PerUser> store extensions to this
+format, such as C<user:username>.
+
+It is suggested that the store should split on the colon and store the
+data more efficiently - the API should remain stable, with the possible
+addition of new prefixes in the future.
+
+For example, C<Store::DBI> maps C<expires:id> a column of C<session:id>
+by special-casing C<get_session_data> and C<store_session_data> for that
+key format, in order to ease the implementation of
+C<delete_expired_sessions>.
+
+The only assurance stores are requred to make is that given
+
+ $c->store_session_data( $x, $y );
+
+for any $x,
+
+ $y == $c->get_session_data( $x )
+
+will hold.
+
+=item store_session_data ( $key, $data )
+
+Store a session whose KEY is the first parameter and data is the second
+parameter in storage.
+
+The second parameter is a hash reference, which should normally be
+serialized (and later deserialized by C<get_session_data>).
+
+=item delete_session_data ( $key )
+
+Delete the session whose KEY is the parameter.
+
+=item delete_expired_sessions
+
+This method is not called by any code at present, but may be called in the
+future, as part of a Catalyst-specific maintenance script.
+
+If you are wrapping around a backend which manages its own auto expiry
+you can just give this method an empty body.
+
+=back
+
+=head2 Error handling
+
+All errors should be thrown using L<Catalyst::Exception>. Return values
+are not checked, and are assumed to be OK. Missing values are not errors.
+
+=head2 Auto-Expiry on the Backend
+
+Storage plugins are encouraged to use C<< $c->session_expires >>, C<<
+$c->config->{session}{expires} >>, or the storage of the
+C<expires:$sessionid> key to perform more efficient expiration, but only
+for the key prefixes C<session>, C<flash> and C<expires>.
+
+If the backend chooses not to do so, L<Catalyst::Plugin::Session> will
+detect expired sessions as they are retrieved and delete them if
+necessary.
+
+Note that session store that use this approach may leak disk space,
+since nothing will actively delete an expired session. The
+C<delete_expired_sessions> method is there so that regularly scheduled
+maintenance scripts can give your backend the opportunity to clean up.
+
+=cut
+
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Test/Store.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Test/Store.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Test/Store.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,189 @@
+#!/usr/bin/perl
+
+package Catalyst::Plugin::Session::Test::Store;
+
+use strict;
+use warnings;
+
+use utf8;
+
+use Test::More;
+use File::Temp;
+use File::Spec;
+
+use Catalyst ();
+
+sub import {
+ shift;
+ my %args = @_;
+
+ plan tests => 19 + ($args{extra_tests} || 0);
+
+ my $backend = $args{backend};
+ my $cfg = $args{config};
+
+ my $p = "Session::Store::$backend";
+ use_ok( my $m = "Catalyst::Plugin::$p" );
+
+ isa_ok( bless( {}, $m ), "Catalyst::Plugin::Session::Store" );
+
+ {
+ package Catalyst::Plugin::SessionStateTest;
+ use base qw/Catalyst::Plugin::Session::State/;
+
+ no strict 'refs';
+
+ sub get_session_id {
+ my $c = shift;
+ ${ ref($c) . "::session_id" };
+ }
+
+ sub set_session_id {
+ my ( $c, $sid ) = @_;
+ ${ ref($c) . "::session_id" } = $sid;
+ }
+
+ sub delete_session_id {
+ my $c = shift;
+ undef ${ ref($c) . "::session_id" };
+ }
+ }
+
+ {
+
+ package SessionStoreTest;
+ use Catalyst qw/Session SessionStateTest/;
+ push our (@ISA), $m;
+
+ use strict;
+ use warnings;
+
+ use Test::More;
+
+ sub create_session : Global {
+ my ( $self, $c ) = @_;
+ ok( !$c->session_is_valid, "no session id yet" );
+ ok( $c->session, "session created" );
+ ok( $c->session_is_valid, "with a session id" );
+
+ $c->session->{magic} = "møøse";
+ }
+
+ sub recover_session : Global {
+ my ( $self, $c ) = @_;
+ ok( $c->session_is_valid, "session id exists" );
+ is( $c->sessionid, our $session_id,
+ "and is the one we saved in the last action" );
+ ok( $c->session, "a session exists" );
+ is( $c->session->{magic},
+ "møøse",
+ "and it contains what we put in on the last attempt" );
+ $c->delete_session("user logout");
+ }
+
+ sub after_session : Global {
+ my ( $self, $c ) = @_;
+ ok( !$c->session_is_valid, "no session id" );
+ ok( !$c->session->{magic}, "session data not restored" );
+ ok( !$c->session_delete_reason, "no reason for deletion" );
+ }
+
+ @{ __PACKAGE__->config->{session} }{ keys %$cfg } = values %$cfg;
+
+ __PACKAGE__->setup;
+ }
+
+ {
+
+ package SessionStoreTest2;
+ use Catalyst qw/Session SessionStateTest/;
+ push our (@ISA), $m;
+
+ our $VERSION = "123";
+
+ use Test::More;
+
+ sub create_session : Global {
+ my ( $self, $c ) = @_;
+
+ $c->session->{magic} = "møøse";
+ }
+
+ sub recover_session : Global {
+ my ( $self, $c ) = @_;
+
+ ok( !$c->session_is_valid, "session is gone" );
+
+ is(
+ $c->session_delete_reason,
+ "session expired",
+ "reason is that the session expired"
+ );
+
+ ok( !$c->session->{magic}, "no saved data" );
+ }
+
+ __PACKAGE__->config->{session}{expires} = 0;
+
+ @{ __PACKAGE__->config->{session} }{ keys %$cfg } = values %$cfg;
+
+ __PACKAGE__->setup;
+ }
+
+ use Test::More;
+
+ can_ok( $m, "get_session_data" );
+ can_ok( $m, "store_session_data" );
+ can_ok( $m, "delete_session_data" );
+ can_ok( $m, "delete_expired_sessions" );
+
+ {
+
+ package t1;
+ use Catalyst::Test "SessionStoreTest";
+
+ # idiotic void context warning workaround
+
+ my $x = get("/create_session");
+ $x = get("/recover_session");
+ $x = get("/after_session");
+ }
+
+ {
+
+ package t2;
+ use Catalyst::Test "SessionStoreTest2";
+
+ my $x = get("/create_session");
+ sleep 1; # let the session expire
+ $x = get("/recover_session");
+ }
+}
+
+__PACKAGE__;
+
+__END__
+
+=pod
+
+=head1 NAME
+
+Catalyst::Plugin::Session::Test::Store - Reusable sanity for session storage
+engines.
+
+=head1 SYNOPSIS
+
+ #!/usr/bin/perl
+
+ use Catalyst::Plugin::Session::Test::Store (
+ backend => "FastMmap",
+ config => {
+ storage => "/tmp/foo",
+ },
+ );
+
+=head1 DESCRIPTION
+
+=cut
+
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Tutorial.pod
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Tutorial.pod (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session/Tutorial.pod 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,323 @@
+=pod
+
+=head1 NAME
+
+Catalyst::Plugin::Session::Tutorial - Understanding and using sessions.
+
+=head1 ASSUMPTIONS
+
+This tutorial assumes that you are familiar with web applications in
+general and Catalyst specifically (up to models and configuration), and
+that you know what HTTP is.
+
+=head1 WHAT ARE SESSIONS
+
+When users use a site, especially one that knows who they are (sites you log in
+to, sites which let you keep a shopping cart, etc.), the server preparing the
+content has to know that request X comes from client A while request Y comes
+from client B, so that each user gets the content meant for it.
+
+The problem is that HTTP is a stateless protocol. This means that every request
+is distinct, and even if it comes from the same client, it's difficult to know
+that.
+
+The way sessions are maintained between distinct requests is that the client
+says, for every request, "I'm client A" or "I'm client B".
+
+This piece of data that tells the server "I'm X" is called the session ID, and
+the threading of several requests together is called a session.
+
+=head1 HOW SESSIONS WORK
+
+=head2 Cookies
+
+HTTP has a feature that lets this become easier, called cookies. A cookie is
+something the server asks the client to save somewhere, and resend every time a
+request is made.
+
+The way they work is that the server sends the C<Set-Cookie> header, with a
+cookie name, a value, and some metadata (like when it expires, what paths it
+applies to, etc.). The client saves this.
+
+Then, on every subsequent request the client will send a C<Cookie> header, with
+the cookie name and value.
+
+=head2 Cookie Alternatives
+
+Another way is to make sure that the session ID is repeated is to include it in
+every URI.
+
+This can be as either a part of the path, or as a query parameter.
+
+This technique has several issues which are discussed in
+L<Catalyst::Plugin::Session::State::URI/CAVEATS>.
+
+=head2 Server-Side Behavior
+
+When the server receives the session ID it can then look this key up in a
+database of some sort. For example the database can contain a shopping cart's
+contents, user preferences, etc.
+
+=head1 USING SESSIONS
+
+In L<Catalyst>, the L<Catalyst::Plugin::Session> plugin provides an API for
+convenient handling of session data. This API is based on the older, less
+flexible and less reliable L<Catalyst::Plugin::Session::FastMmap>.
+
+The plugin is modular, and requires backend plugins to be used.
+
+=head2 State Plugins
+
+State plugins handle session ID persistence. For example
+L<Catalyst::Plugin::Session::State::Cookie> creates a cookie with the session
+ID in it.
+
+These plugins will automatically set C<< $c->sessionid >> at the begining of
+the request, and automatically cause C<< $c->sessionid >> to be saved by the
+client at the end of the request.
+
+=head2 Store Plugins
+
+The backend into which session data is stored is provided by these plugins. For
+example, L<Catalyst::Plugin::Session::Store::DBI> uses a database table to
+store session data, while L<Catalyst::Plugin::Session::Store::FastMmap> uses
+L<Cache::FastMmap>.
+
+=head2 Configuration
+
+First you need to load the appropriate plugins into your L<Catalyst>
+application:
+
+ package MyApp;
+
+ use Catalyst qw/
+ Session
+ Session::State::Cookie
+ Session::Store::File
+ /;
+
+This loads the session API, as well as the required backends of your choice.
+
+After the plugins are loaded they need to be configured. This is done according
+to L<Catalyst::Manual::Cookbook/Configure_your_application>.
+
+Each backend plugin requires its own configuration options (with most plugins
+providing sensible defaults). The session API itself also has configurable
+options listed in L<Catalyst::Plugin::Session/CONFIGURATION>.
+
+For the plugins above we don't need any configuration at all - they should work
+out of the box, but suppose we did want to change some things around, it'll
+look like this:
+
+ MyApp->config( session => {
+ cookie_name => "my_fabulous_cookie",
+ storage => "/path/to/store_data_file",
+ });
+
+=head2 Usage
+
+Now, let's say we have an online shop, and the user is adding an item to the
+shopping cart.
+
+Typically the item the user was viewing would have a form or link that adds the
+item to the cart.
+
+Suppose this link goes to C</cart/add/foo_baz/2>, meaning that we want two
+units of the item C<foo_baz> to be added to the cart.
+
+Our C<add> action should look something like this:
+
+ package MyApp::Controller::Cart;
+
+ sub add : Local {
+ my ( $self, $c, $item_id, $quantity ) = @_;
+ $quantity ||= 1;
+
+ if ( $c->model("Items")->item_exists($item_id) ) {
+ $c->session->{cart}{$item_id} += $quantity;
+ } else {
+ die "No such item";
+ }
+ }
+
+The way this works is that C<< $c->session >> always returns a hash reference
+to some data which is stored by the storage backend plugin. The hash reference
+returned always contains the same items that were in there at the end of the
+last request.
+
+All the mishmash described above is done automatically. First, the method looks
+to see if a session ID is set. This session ID will be set by the State plugin
+if appropriate, at the start of the request (e.g. by looking at the cookies
+sent by the client).
+
+If a session ID is set, the store will be asked to retrieve the session
+data for that specific session ID, and this is returned from
+C<< $c->session >>. This retrieval is cached, and will only happen once per
+request, if at all.
+
+If a session ID is not set, a new one is generated, a new anonymous hash is
+created and saved in the store with the session ID as the key, and the
+reference to the hash is returned.
+
+The action above takes this hash reference, and updates a nested hash within
+it, that counts quantity of each item as stored in the cart.
+
+Any cart-listing code can then look into the session data and use it to display
+the correct items, which will, of course, be remembered across requests.
+
+Here is an action some Template Toolkit example code that could be used to
+generate a cart listing:
+
+ sub list_cart : Local {
+ my ( $self, $c ) = @_;
+
+ # get the cart data, that maps from item_id to quantity
+ my $cart = $c->session->{cart} || {};
+
+ # this is our abstract model in which items are stored
+ my $storage = $c->model("Items");
+
+ # map from item_id to item (an object or hash reference)
+ my %items = map { $_ => $storage->get_item($_) } keys %$cart;
+
+ # put the relevant info on the stash
+ $c->stash->{cart}{items} = \%items;
+ $c->stash->{cart}{quantity} = $cart;
+ }
+
+And [a part of] the template it forwards to:
+
+ <table>
+
+ <thead>
+ <tr>
+ <th>Item</th>
+ <th>Quantity</th>
+ <th>Price</th>
+ <th>remove</th>
+ </tr>
+ </thead>
+
+ <tbody>
+ [%# the table body lists all the items in the cart %]
+ [% FOREACH item_id = cart.items.keys %]
+
+ [%# each item has its own row in the table %]
+
+ [% item = cart.items.$item_id %]
+ [% quantity = cart.quantity.$item_id %]
+
+ <tr>
+ <td>
+ [%# item.name is an attribute in the item
+ # object, as loaded from the store %]
+ [% item.name %]
+ </td>
+
+ <td>
+ [%# supposedly this is part of a form where you
+ # can update the quantity %]
+ <input type="text" name="[% item_id %]_quantity"
+ value="[% quantity %]" />
+ </td>
+
+ <td> $ [% item.price * quantity %] </td>
+
+ <td>
+ <a href="[% c.uri_for('/cart/remove') %]/[% item_id %]">
+ <img src="/static/trash_can.png" />
+ </a>
+ </td>
+ [% END %]
+ <tbody>
+
+ <tfoot>
+ <tr>
+ <td colspan="2"> Total: </td>
+ <td>
+ [%# calculate sum in this cell - too
+ # much headache for a tutorial ;-) %]
+ </td>
+ <td>
+ <a href="[% c.uri_for('/cart/empty') %]">Empty cart</a>
+ </td>
+ </tr>
+ </tfoot>
+
+ </table>
+
+As you can see the way that items are added into C<< $c->session->{cart} >> is
+pretty simple. Since C<< $c->session >> is restored as necessary, and contains
+data from previous requests by the same client, the cart can be updated as the
+user navigates the site pretty transparently.
+
+=head1 SECURITY ISSUES
+
+These issues all relate to how session data is managed, as described above.
+These are not issues you should be concerned about in your application code,
+but are here for their educational value.
+
+=head2 (Not) Trusting the Client
+
+In order to avoid the overhead of server-side data storage, the session data can
+be included in the cookie itself.
+
+There are two problems with this:
+
+=over 4
+
+=item 1
+
+The user can change the data.
+
+=item 2
+
+Cookies have a 4 kilobyte size limit.
+
+The size limit is of no concern in this section, but data changing is. In the
+database scheme the data can be trusted, since the user can neither read nor
+write it. However, if the data is delegated to the user, then special measures
+have to be added for ensuring data integrity, and perhaps secrecy too.
+
+This can be implemented by encrypting and signing the cookie data, but this is
+a big headache.
+
+=back
+
+=head2 Session Hijacking
+
+What happens when client B says "I'm client A"? Well, basically, the server
+buys it. There's no real way around it.
+
+The solution is to make "I'm client A" a difficult thing to say. This is why
+session IDs are randomized. If they are properly randomized, session IDs are so
+hard to guess that they must be stolen instead.
+
+This is called session hijacking. There are several ways one might hijack
+another user's session.
+
+=head3 Cross Site Scripting
+
+One is by using cross site scripting attacks to steal the cookie data. In
+community sites, where users can cause the server to display arbitrary HTML,
+they can use this to put JavaScript code on the server.
+
+If the server does not enforce a strict subset of tags that may be used, the
+malicious user could use this code to steal the cookies (there is a JavaScript
+API that lets cookies be accessed, but this code has to be run on the same
+website that the cookie came from).
+
+=head3 Social Engineering
+
+By tricking a user into revealing a URI with session data embedded in it (when
+cookies are not used), the session ID can also be stolen.
+
+Also, a naive user could be tricked into showing the cookie data from the
+browser to a malicious user.
+
+=head1 AUTHOR
+
+Yuval Kogman E<lt>nothingmuch at woobling.orgE<gt>
+
+=cut
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/lib/Catalyst/Plugin/Session.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,1027 @@
+#!/usr/bin/perl
+
+package Catalyst::Plugin::Session;
+use base qw/Class::Accessor::Fast/;
+
+use strict;
+use warnings;
+
+use NEXT;
+use Catalyst::Exception ();
+use Digest ();
+use overload ();
+use Object::Signature ();
+use Carp;
+
+our $VERSION = '0.20';
+
+my @session_data_accessors; # used in delete_session
+BEGIN {
+ __PACKAGE__->mk_accessors(
+ "_session_delete_reason",
+ @session_data_accessors = qw/
+ _sessionid
+ _session
+ _session_expires
+ _extended_session_expires
+ _session_data_sig
+ _flash
+ _flash_keep_keys
+ _flash_key_hashes
+ _tried_loading_session_id
+ _tried_loading_session_data
+ _tried_loading_session_expires
+ _tried_loading_flash_data
+ /
+ );
+}
+
+sub setup {
+ my $c = shift;
+
+ $c->NEXT::setup(@_);
+
+ $c->check_session_plugin_requirements;
+ $c->setup_session;
+
+ return $c;
+}
+
+sub check_session_plugin_requirements {
+ my $c = shift;
+
+ unless ( $c->isa("Catalyst::Plugin::Session::State")
+ && $c->isa("Catalyst::Plugin::Session::Store") )
+ {
+ my $err =
+ ( "The Session plugin requires both Session::State "
+ . "and Session::Store plugins to be used as well." );
+
+ $c->log->fatal($err);
+ Catalyst::Exception->throw($err);
+ }
+}
+
+sub setup_session {
+ my $c = shift;
+
+ my $cfg = ( $c->config->{session} ||= {} );
+
+ %$cfg = (
+ expires => 7200,
+ verify_address => 0,
+ %$cfg,
+ );
+
+ $c->NEXT::setup_session();
+}
+
+sub prepare_action {
+ my $c = shift;
+
+ if ( $c->config->{session}{flash_to_stash}
+ and $c->sessionid
+ and my $flash_data = $c->flash )
+ {
+ @{ $c->stash }{ keys %$flash_data } = values %$flash_data;
+ }
+
+ $c->NEXT::prepare_action(@_);
+}
+
+sub finalize_headers {
+ my $c = shift;
+
+ # fix cookie before we send headers
+ $c->_save_session_expires;
+
+ return $c->NEXT::finalize_headers(@_);
+}
+
+sub finalize {
+ my $c = shift;
+ my $ret = $c->NEXT::finalize(@_);
+
+ # then finish the rest
+ $c->finalize_session;
+ return $ret;
+}
+
+sub finalize_session {
+ my $c = shift;
+
+ $c->NEXT::finalize_session;
+
+ $c->_save_session_id;
+ $c->_save_session;
+ $c->_save_flash;
+
+ $c->_clear_session_instance_data;
+}
+
+sub _save_session_id {
+ my $c = shift;
+
+ # we already called set when allocating
+ # no need to tell the state plugins anything new
+}
+
+sub _save_session_expires {
+ my $c = shift;
+
+ if ( defined($c->_session_expires) ) {
+ my $expires = $c->session_expires; # force extension
+
+ my $sid = $c->sessionid;
+ $c->store_session_data( "expires:$sid" => $expires );
+ }
+}
+
+sub _save_session {
+ my $c = shift;
+
+ if ( my $session_data = $c->_session ) {
+
+ no warnings 'uninitialized';
+ if ( Object::Signature::signature($session_data) ne
+ $c->_session_data_sig )
+ {
+ $session_data->{__updated} = time();
+ my $sid = $c->sessionid;
+ $c->store_session_data( "session:$sid" => $session_data );
+ }
+ }
+}
+
+sub _save_flash {
+ my $c = shift;
+
+ if ( my $flash_data = $c->_flash ) {
+
+ my $hashes = $c->_flash_key_hashes || {};
+ my $keep = $c->_flash_keep_keys || {};
+ foreach my $key ( keys %$hashes ) {
+ if ( !exists $keep->{$key} and Object::Signature::signature( \$flash_data->{$key} ) eq $hashes->{$key} ) {
+ delete $flash_data->{$key};
+ }
+ }
+
+ my $sid = $c->sessionid;
+
+ my $session_data = $c->_session;
+ if (%$flash_data) {
+ $session_data->{__flash} = $flash_data;
+ }
+ else {
+ delete $session_data->{__flash};
+ }
+ $c->_session($session_data);
+ $c->_save_session;
+ }
+}
+
+sub _load_session_expires {
+ my $c = shift;
+ return $c->_session_expires if $c->_tried_loading_session_expires;
+ $c->_tried_loading_session_expires(1);
+
+ if ( my $sid = $c->sessionid ) {
+ my $expires = $c->get_session_data("expires:$sid") || 0;
+
+ if ( $expires >= time() ) {
+ $c->_session_expires( $expires );
+ return $expires;
+ } else {
+ $c->delete_session( "session expired" );
+ return 0;
+ }
+ }
+
+ return;
+}
+
+sub _load_session {
+ my $c = shift;
+ return $c->_session if $c->_tried_loading_session_data;
+ $c->_tried_loading_session_data(1);
+
+ if ( my $sid = $c->sessionid ) {
+ if ( $c->_load_session_expires ) { # > 0
+
+ my $session_data = $c->get_session_data("session:$sid") || return;
+ $c->_session($session_data);
+
+ no warnings 'uninitialized'; # ne __address
+ if ( $c->config->{session}{verify_address}
+ && $session_data->{__address} ne $c->request->address )
+ {
+ $c->log->warn(
+ "Deleting session $sid due to address mismatch ("
+ . $session_data->{__address} . " != "
+ . $c->request->address . ")"
+ );
+ $c->delete_session("address mismatch");
+ return;
+ }
+
+ $c->log->debug(qq/Restored session "$sid"/) if $c->debug;
+ $c->_session_data_sig( Object::Signature::signature($session_data) ) if $session_data;
+ $c->_expire_session_keys;
+
+ return $session_data;
+ }
+ }
+
+ return;
+}
+
+sub _load_flash {
+ my $c = shift;
+ return $c->_flash if $c->_tried_loading_flash_data;
+ $c->_tried_loading_flash_data(1);
+
+ if ( my $sid = $c->sessionid ) {
+
+ my $session_data = $c->session;
+ $c->_flash($session_data->{__flash});
+
+ if ( my $flash_data = $c->_flash )
+ {
+ $c->_flash_key_hashes({ map { $_ => Object::Signature::signature( \$flash_data->{$_} ) } keys %$flash_data });
+
+ return $flash_data;
+ }
+ }
+
+ return;
+}
+
+sub _expire_session_keys {
+ my ( $c, $data ) = @_;
+
+ my $now = time;
+
+ my $expire_times = ( $data || $c->_session || {} )->{__expire_keys} || {};
+ foreach my $key ( grep { $expire_times->{$_} < $now } keys %$expire_times ) {
+ delete $c->_session->{$key};
+ delete $expire_times->{$key};
+ }
+}
+
+sub _clear_session_instance_data {
+ my $c = shift;
+ $c->$_(undef) for @session_data_accessors;
+ $c->NEXT::_clear_session_instance_data; # allow other plugins to hook in on this
+}
+
+sub delete_session {
+ my ( $c, $msg ) = @_;
+
+ $c->log->debug("Deleting session" . ( defined($msg) ? "($msg)" : '(no reason given)') ) if $c->debug;
+
+ # delete the session data
+ if ( my $sid = $c->sessionid ) {
+ $c->delete_session_data("${_}:${sid}") for qw/session expires flash/;
+ $c->delete_session_id($sid);
+ }
+
+ # reset the values in the context object
+ # see the BEGIN block
+ $c->_clear_session_instance_data;
+
+ $c->_session_delete_reason($msg);
+}
+
+sub session_delete_reason {
+ my $c = shift;
+
+ $c->session_is_valid; # check that it was loaded
+
+ $c->_session_delete_reason(@_);
+}
+
+sub session_expires {
+ my $c = shift;
+
+ if ( defined( my $expires = $c->_extended_session_expires ) ) {
+ return $expires;
+ } elsif ( defined( $expires = $c->_load_session_expires ) ) {
+ return $c->extend_session_expires( $expires );
+ } else {
+ return 0;
+ }
+}
+
+sub extend_session_expires {
+ my ( $c, $expires ) = @_;
+ $c->_extended_session_expires( my $updated = $c->calculate_extended_session_expires( $expires ) );
+ $c->extend_session_id( $c->sessionid, $updated );
+ return $updated;
+}
+
+sub calculate_initial_session_expires {
+ my $c = shift;
+ return ( time() + $c->config->{session}{expires} );
+}
+
+sub calculate_extended_session_expires {
+ my ( $c, $prev ) = @_;
+ $c->calculate_initial_session_expires;
+}
+
+sub reset_session_expires {
+ my ( $c, $sid ) = @_;
+
+ my $exp = $c->calculate_initial_session_expires;
+ $c->_session_expires( $exp );
+ $c->_extended_session_expires( $exp );
+ $exp;
+}
+
+sub sessionid {
+ my $c = shift;
+
+ return $c->_sessionid || $c->_load_sessionid;
+}
+
+sub _load_sessionid {
+ my $c = shift;
+ return if $c->_tried_loading_session_id;
+ $c->_tried_loading_session_id(1);
+
+ if ( defined( my $sid = $c->get_session_id ) ) {
+ if ( $c->validate_session_id($sid) ) {
+ # temporarily set the inner key, so that validation will work
+ $c->_sessionid($sid);
+ return $sid;
+ } else {
+ my $err = "Tried to set invalid session ID '$sid'";
+ $c->log->error($err);
+ Catalyst::Exception->throw($err);
+ }
+ }
+
+ return;
+}
+
+sub session_is_valid {
+ my $c = shift;
+
+ # force a check for expiry, but also __address, etc
+ if ( $c->_load_session ) {
+ return 1;
+ } else {
+ return;
+ }
+}
+
+sub validate_session_id {
+ my ( $c, $sid ) = @_;
+
+ $sid and $sid =~ /^[a-f\d]+$/i;
+}
+
+sub session {
+ my $c = shift;
+
+ $c->_session || $c->_load_session || do {
+ $c->create_session_id_if_needed;
+ $c->initialize_session_data;
+ };
+}
+
+sub keep_flash {
+ my ( $c, @keys ) = @_;
+ my $href = $c->_flash_keep_keys || $c->_flash_keep_keys({});
+ (@{$href}{@keys}) = ((undef) x @keys);
+}
+
+sub _flash_data {
+ my $c = shift;
+ $c->_flash || $c->_load_flash || do {
+ $c->create_session_id_if_needed;
+ $c->_flash( {} );
+ };
+}
+
+sub _set_flash {
+ my $c = shift;
+ if (@_) {
+ my $items = @_ > 1 ? {@_} : $_[0];
+ croak('flash takes a hash or hashref') unless ref $items;
+ @{ $c->_flash }{ keys %$items } = values %$items;
+ }
+}
+
+sub flash {
+ my $c = shift;
+ $c->_flash_data;
+ $c->_set_flash(@_);
+ return $c->_flash;
+}
+
+sub clear_flash {
+ my $c = shift;
+
+ #$c->delete_session_data("flash:" . $c->sessionid); # should this be in here? or delayed till finalization?
+ $c->_flash_key_hashes({});
+ $c->_flash_keep_keys({});
+ $c->_flash({});
+}
+
+sub session_expire_key {
+ my ( $c, %keys ) = @_;
+
+ my $now = time;
+ @{ $c->session->{__expire_keys} }{ keys %keys } =
+ map { $now + $_ } values %keys;
+}
+
+sub initialize_session_data {
+ my $c = shift;
+
+ my $now = time;
+
+ return $c->_session(
+ {
+ __created => $now,
+ __updated => $now,
+
+ (
+ $c->config->{session}{verify_address}
+ ? ( __address => $c->request->address )
+ : ()
+ ),
+ }
+ );
+}
+
+sub generate_session_id {
+ my $c = shift;
+
+ my $digest = $c->_find_digest();
+ $digest->add( $c->session_hash_seed() );
+ return $digest->hexdigest;
+}
+
+sub create_session_id_if_needed {
+ my $c = shift;
+ $c->create_session_id unless $c->sessionid;
+}
+
+sub create_session_id {
+ my $c = shift;
+
+ my $sid = $c->generate_session_id;
+
+ $c->log->debug(qq/Created session "$sid"/) if $c->debug;
+
+ $c->_sessionid($sid);
+ $c->reset_session_expires;
+ $c->set_session_id($sid);
+
+ return $sid;
+}
+
+my $counter;
+
+sub session_hash_seed {
+ my $c = shift;
+
+ return join( "", ++$counter, time, rand, $$, {}, overload::StrVal($c), );
+}
+
+my $usable;
+
+sub _find_digest () {
+ unless ($usable) {
+ foreach my $alg (qw/SHA-1 SHA-256 MD5/) {
+ if ( eval { Digest->new($alg) } ) {
+ $usable = $alg;
+ last;
+ }
+ }
+ Catalyst::Exception->throw(
+ "Could not find a suitable Digest module. Please install "
+ . "Digest::SHA1, Digest::SHA, or Digest::MD5" )
+ unless $usable;
+ }
+
+ return Digest->new($usable);
+}
+
+sub dump_these {
+ my $c = shift;
+
+ (
+ $c->NEXT::dump_these(),
+
+ $c->sessionid
+ ? ( [ "Session ID" => $c->sessionid ], [ Session => $c->session ], )
+ : ()
+ );
+}
+
+
+sub get_session_id { shift->NEXT::get_session_id(@_) }
+sub set_session_id { shift->NEXT::set_session_id(@_) }
+sub delete_session_id { shift->NEXT::delete_session_id(@_) }
+sub extend_session_id { shift->NEXT::extend_session_id(@_) }
+
+__PACKAGE__;
+
+__END__
+
+=pod
+
+=head1 NAME
+
+Catalyst::Plugin::Session - Generic Session plugin - ties together server side storage and client side state required to maintain session data.
+
+=head1 SYNOPSIS
+
+ # To get sessions to "just work", all you need to do is use these plugins:
+
+ use Catalyst qw/
+ Session
+ Session::Store::FastMmap
+ Session::State::Cookie
+ /;
+
+ # you can replace Store::FastMmap with Store::File - both have sensible
+ # default configurations (see their docs for details)
+
+ # more complicated backends are available for other scenarios (DBI storage,
+ # etc)
+
+
+ # after you've loaded the plugins you can save session data
+ # For example, if you are writing a shopping cart, it could be implemented
+ # like this:
+
+ sub add_item : Local {
+ my ( $self, $c ) = @_;
+
+ my $item_id = $c->req->param("item");
+
+ # $c->session is a hash ref, a bit like $c->stash
+ # the difference is that it' preserved across requests
+
+ push @{ $c->session->{items} }, $item_id;
+
+ $c->forward("MyView");
+ }
+
+ sub display_items : Local {
+ my ( $self, $c ) = @_;
+
+ # values in $c->session are restored
+ $c->stash->{items_to_display} =
+ [ map { MyModel->retrieve($_) } @{ $c->session->{items} } ];
+
+ $c->forward("MyView");
+ }
+
+=head1 DESCRIPTION
+
+The Session plugin is the base of two related parts of functionality required
+for session management in web applications.
+
+The first part, the State, is getting the browser to repeat back a session key,
+so that the web application can identify the client and logically string
+several requests together into a session.
+
+The second part, the Store, deals with the actual storage of information about
+the client. This data is stored so that the it may be revived for every request
+made by the same client.
+
+This plugin links the two pieces together.
+
+=head1 RECOMENDED BACKENDS
+
+=over 4
+
+=item Session::State::Cookie
+
+The only really sane way to do state is using cookies.
+
+=item Session::Store::File
+
+A portable backend, based on Cache::File.
+
+=item Session::Store::FastMmap
+
+A fast and flexible backend, based on Cache::FastMmap.
+
+=back
+
+=head1 METHODS
+
+=over 4
+
+=item sessionid
+
+An accessor for the session ID value.
+
+=item session
+
+Returns a hash reference that might contain unserialized values from previous
+requests in the same session, and whose modified value will be saved for future
+requests.
+
+This method will automatically create a new session and session ID if none
+exists.
+
+=item session_expires
+
+=item session_expires $reset
+
+This method returns the time when the current session will expire, or 0 if
+there is no current session. If there is a session and it already expired, it
+will delete the session and return 0 as well.
+
+If the C<$reset> parameter is true, and there is a session ID the expiry time
+will be reset to the current time plus the time to live (see
+L</CONFIGURATION>). This is used when creating a new session.
+
+=item flash
+
+This is like Ruby on Rails' flash data structure. Think of it as a stash that
+lasts for longer than one request, letting you redirect instead of forward.
+
+The flash data will be cleaned up only on requests on which actually use
+$c->flash (thus allowing multiple redirections), and the policy is to delete
+all the keys which haven't changed since the flash data was loaded at the end
+of every request.
+
+ sub moose : Local {
+ my ( $self, $c ) = @_;
+
+ $c->flash->{beans} = 10;
+ $c->response->redirect( $c->uri_for("foo") );
+ }
+
+ sub foo : Local {
+ my ( $self, $c ) = @_;
+
+ my $value = $c->flash->{beans};
+
+ # ...
+
+ $c->response->redirect( $c->uri_for("bar") );
+ }
+
+ sub bar : Local {
+ my ( $self, $c ) = @_;
+
+ if ( exists $c->flash->{beans} ) { # false
+
+ }
+ }
+
+=item clear_flash
+
+Zap all the keys in the flash regardless of their current state.
+
+=item keep_flash @keys
+
+If you want to keep a flash key for the next request too, even if it hasn't
+changed, call C<keep_flash> and pass in the keys as arguments.
+
+=item delete_session REASON
+
+This method is used to invalidate a session. It takes an optional parameter
+which will be saved in C<session_delete_reason> if provided.
+
+NOTE: This method will B<also> delete your flash data.
+
+=item session_delete_reason
+
+This accessor contains a string with the reason a session was deleted. Possible
+values include:
+
+=over 4
+
+=item *
+
+C<address mismatch>
+
+=item *
+
+C<session expired>
+
+=back
+
+=item session_expire_key $key, $ttl
+
+Mark a key to expire at a certain time (only useful when shorter than the
+expiry time for the whole session).
+
+For example:
+
+ __PACKAGE__->config->{session}{expires} = 1000000000000; # forever
+
+ # later
+
+ $c->session_expire_key( __user => 3600 );
+
+Will make the session data survive, but the user will still be logged out after
+an hour.
+
+Note that these values are not auto extended.
+
+=back
+
+=head1 INTERNAL METHODS
+
+=over 4
+
+=item setup
+
+This method is extended to also make calls to
+C<check_session_plugin_requirements> and C<setup_session>.
+
+=item check_session_plugin_requirements
+
+This method ensures that a State and a Store plugin are also in use by the
+application.
+
+=item setup_session
+
+This method populates C<< $c->config->{session} >> with the default values
+listed in L</CONFIGURATION>.
+
+=item prepare_action
+
+This method is extended.
+
+Its only effect is if the (off by default) C<flash_to_stash> configuration
+parameter is on - then it will copy the contents of the flash to the stash at
+prepare time.
+
+=item finalize_headers
+
+This method is extended and will extend the expiry time before sending
+the response.
+
+=item finalize
+
+This method is extended and will call finalize_session after the other
+finalizes run. Here we persist the session data if a session exists.
+
+=item initialize_session_data
+
+This method will initialize the internal structure of the session, and is
+called by the C<session> method if appropriate.
+
+=item create_session_id
+
+Creates a new session ID using C<generate_session_id> if there is no session ID
+yet.
+
+=item validate_session_id SID
+
+Make sure a session ID is of the right format.
+
+This currently ensures that the session ID string is any amount of case
+insensitive hexadecimal characters.
+
+=item generate_session_id
+
+This method will return a string that can be used as a session ID. It is
+supposed to be a reasonably random string with enough bits to prevent
+collision. It basically takes C<session_hash_seed> and hashes it using SHA-1,
+MD5 or SHA-256, depending on the availability of these modules.
+
+=item session_hash_seed
+
+This method is actually rather internal to generate_session_id, but should be
+overridable in case you want to provide more random data.
+
+Currently it returns a concatenated string which contains:
+
+=over 4
+
+=item * A counter
+
+=item * The current time
+
+=item * One value from C<rand>.
+
+=item * The stringified value of a newly allocated hash reference
+
+=item * The stringified value of the Catalyst context object
+
+=back
+
+in the hopes that those combined values are entropic enough for most uses. If
+this is not the case you can replace C<session_hash_seed> with e.g.
+
+ sub session_hash_seed {
+ open my $fh, "<", "/dev/random";
+ read $fh, my $bytes, 20;
+ close $fh;
+ return $bytes;
+ }
+
+Or even more directly, replace C<generate_session_id>:
+
+ sub generate_session_id {
+ open my $fh, "<", "/dev/random";
+ read $fh, my $bytes, 20;
+ close $fh;
+ return unpack("H*", $bytes);
+ }
+
+Also have a look at L<Crypt::Random> and the various openssl bindings - these
+modules provide APIs for cryptographically secure random data.
+
+=item finalize_session
+
+Clean up the session during C<finalize>.
+
+This clears the various accessors after saving to the store.
+
+=item dump_these
+
+See L<Catalyst/dump_these> - ammends the session data structure to the list of
+dumped objects if session ID is defined.
+
+
+=item calculate_extended_session_expires
+
+=item calculate_initial_session_expires
+
+=item create_session_id_if_needed
+
+=item delete_session_id
+
+=item extend_session_expires
+
+=item extend_session_id
+
+=item get_session_id
+
+=item reset_session_expires
+
+=item session_is_valid
+
+=item set_session_id
+
+=back
+
+=head1 USING SESSIONS DURING PREPARE
+
+The earliest point in time at which you may use the session data is after
+L<Catalyst::Plugin::Session>'s C<prepare_action> has finished.
+
+State plugins must set $c->session ID before C<prepare_action>, and during
+C<prepare_action> L<Catalyst::Plugin::Session> will actually load the data from
+the store.
+
+ sub prepare_action {
+ my $c = shift;
+
+ # don't touch $c->session yet!
+
+ $c->NEXT::prepare_action( @_ );
+
+ $c->session; # this is OK
+ $c->sessionid; # this is also OK
+ }
+
+=head1 CONFIGURATION
+
+ $c->config->{session} = {
+ expires => 1234,
+ };
+
+All configuation parameters are provided in a hash reference under the
+C<session> key in the configuration hash.
+
+=over 4
+
+=item expires
+
+The time-to-live of each session, expressed in seconds. Defaults to 7200 (two
+hours).
+
+=item verify_address
+
+When true, C<<$c->request->address>> will be checked at prepare time. If it is
+not the same as the address that initiated the session, the session is deleted.
+
+Defaults to false.
+
+=item flash_to_stash
+
+This option makes it easier to have actions behave the same whether they were
+forwarded to or redirected to. On prepare time it copies the contents of
+C<flash> (if any) to the stash.
+
+=back
+
+=head1 SPECIAL KEYS
+
+The hash reference returned by C<< $c->session >> contains several keys which
+are automatically set:
+
+=over 4
+
+=item __expires
+
+This key no longer exists. Use C<session_expires> instead.
+
+=item __updated
+
+The last time a session was saved to the store.
+
+=item __created
+
+The time when the session was first created.
+
+=item __address
+
+The value of C<< $c->request->address >> at the time the session was created.
+This value is only populated if C<verify_address> is true in the configuration.
+
+=back
+
+=head1 CAVEATS
+
+=head2 Round the Robin Proxies
+
+C<verify_address> could make your site inaccessible to users who are behind
+load balanced proxies. Some ISPs may give a different IP to each request by the
+same client due to this type of proxying. If addresses are verified these
+users' sessions cannot persist.
+
+To let these users access your site you can either disable address verification
+as a whole, or provide a checkbox in the login dialog that tells the server
+that it's OK for the address of the client to change. When the server sees that
+this box is checked it should delete the C<__address> special key from the
+session hash when the hash is first created.
+
+=head2 Race Conditions
+
+In this day and age where cleaning detergents and Dutch football (not the
+American kind) teams roam the plains in great numbers, requests may happen
+simultaneously. This means that there is some risk of session data being
+overwritten, like this:
+
+=over 4
+
+=item 1.
+
+request a starts, request b starts, with the same session ID
+
+=item 2.
+
+session data is loaded in request a
+
+=item 3.
+
+session data is loaded in request b
+
+=item 4.
+
+session data is changed in request a
+
+=item 5.
+
+request a finishes, session data is updated and written to store
+
+=item 6.
+
+request b finishes, session data is updated and written to store, overwriting
+changes by request a
+
+=back
+
+If this is a concern in your application, a soon-to-be-developed locking
+solution is the only safe way to go. This will have a bigger overhead.
+
+For applications where any given user is only making one request at a time this
+plugin should be safe enough.
+
+=head1 AUTHORS
+
+Andy Grundman
+
+Christian Hansen
+
+Yuval Kogman, C<nothingmuch at woobling.org> (current maintainer)
+
+Sebastian Riedel
+
+And countless other contributers from #catalyst. Thanks guys!
+
+=head1 COPYRIGHT & LICENSE
+
+ Copyright (c) 2005 the aforementioned authors. All rights
+ reserved. This program is free software; you can redistribute
+ it and/or modify it under the same terms as Perl itself.
+
+=cut
+
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/00_basic_sanity.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/00_basic_sanity.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/00_basic_sanity.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,11 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More tests => 4;
+
+
+my $m; BEGIN { use_ok($m = "Catalyst::Plugin::Session") }
+
+can_ok($m, $_) for qw/sessionid session session_delete_reason/;
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/01_setup.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/01_setup.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/01_setup.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,73 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More tests => 10;
+use Test::MockObject;
+use Test::Deep;
+
+my $m;
+BEGIN { use_ok( $m = "Catalyst::Plugin::Session" ) }
+
+my %config;
+my $log = Test::MockObject->new;
+my @mock_isa = ();
+
+$log->set_true("fatal");
+
+{
+
+ package MockCxt;
+ use base $m;
+ sub new { bless {}, $_[0] }
+ sub config { \%config }
+ sub log { $log }
+
+ sub isa {
+ my $self = shift;
+ my $class = shift;
+ grep { $_ eq $class } @mock_isa or $self->SUPER::isa($class);
+ }
+}
+
+can_ok( $m, "setup" );
+
+eval { MockCxt->new->setup }; # throws OK is not working with NEXT
+like(
+ $@,
+ qr/requires.*((?:State|Store).*){2}/i,
+ "can't setup an object that doesn't use state/store plugins"
+);
+
+$log->called_ok( "fatal", "fatal error logged" );
+
+ at mock_isa = qw/Catalyst::Plugin::Session::State/;
+eval { MockCxt->new->setup };
+like( $@, qr/requires.*(?:Store)/i,
+ "can't setup an object that doesn't use state/store plugins" );
+
+ at mock_isa = qw/Catalyst::Plugin::Session::Store/;
+eval { MockCxt->new->setup };
+like( $@, qr/requires.*(?:State)/i,
+ "can't setup an object that doesn't use state/store plugins" );
+
+$log->clear;
+
+ at mock_isa =
+ qw/Catalyst::Plugin::Session::State Catalyst::Plugin::Session::Store/;
+eval { MockCxt->new->setup };
+ok( !$@, "setup() lives with state/store plugins in use" );
+ok( !$log->called("fatal"), "no fatal error logged either" );
+
+cmp_deeply(
+ [ keys %{ $config{session} } ],
+ bag(qw/expires verify_address/),
+ "default values for config were populated in successful setup",
+);
+
+%config = ( session => { expires => 1234 } );
+MockCxt->new->setup;
+is( $config{session}{expires},
+ 1234, "user values are not overwritten in config" );
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/03_flash.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/03_flash.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/03_flash.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,75 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More tests => 12;
+use Test::MockObject::Extends;
+use Test::Exception;
+use Test::Deep;
+
+my $m;
+BEGIN { use_ok( $m = "Catalyst::Plugin::Session" ) }
+
+my $c = Test::MockObject::Extends->new($m);
+
+my $flash = {};
+$c->mock(
+ get_session_data => sub {
+ my ( $c, $key ) = @_;
+ return $key =~ /expire/ ? time() + 1000 : $flash;
+ },
+);
+$c->mock("debug" => sub { 0 });
+$c->mock("store_session_data" => sub { $flash = $_[2] });
+$c->mock("delete_session_data" => sub { $flash = {} });
+$c->set_always( _sessionid => "deadbeef" );
+$c->set_always( config => { session => { expires => 1000 } } );
+$c->set_always( stash => {} );
+
+is_deeply( $c->session, {}, "nothing in session" );
+
+is_deeply( $c->flash, {}, "nothing in flash" );
+
+$c->flash->{foo} = "moose";
+
+$c->finalize;
+
+is_deeply( $c->flash, { foo => "moose" }, "one key in flash" );
+
+cmp_deeply( $c->session, { __updated => re('^\d+$'), __flash => $c->flash }, "session has __flash with flash data" );
+
+$c->flash(bar => "gorch");
+
+is_deeply( $c->flash, { foo => "moose", bar => "gorch" }, "two keys in flash" );
+
+cmp_deeply( $c->session, { __updated => re('^\d+$'), __flash => $c->flash }, "session still has __flash with flash data" );
+
+$c->finalize;
+
+is_deeply( $c->flash, { bar => "gorch" }, "one key in flash" );
+
+$c->finalize;
+
+$c->flash->{test} = 'clear_flash';
+
+$c->finalize;
+
+$c->clear_flash();
+
+is_deeply( $c->flash, {}, "nothing in flash after clear_flash" );
+
+$c->finalize;
+
+is_deeply( $c->flash, {}, "nothing in flash after finalize after clear_flash" );
+
+cmp_deeply( $c->session, { __updated => re('^\d+$'), }, "session has empty __flash after clear_flash + finalize" );
+
+$c->flash->{bar} = "gorch";
+
+$c->config->{session}{flash_to_stash} = 1;
+
+$c->finalize;
+$c->prepare_action;
+
+is_deeply( $c->stash, { bar => "gorch" }, "flash copied to stash" );
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/05_semi_persistent_flash.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/05_semi_persistent_flash.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/05_semi_persistent_flash.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,44 @@
+#!/usr/bin/perl -w
+use strict;
+
+use Test::More;
+
+BEGIN {
+ eval { require Catalyst::Plugin::Session::State::Cookie; Catalyst::Plugin::Session::State::Cookie->VERSION(0.03) }
+ or plan skip_all =>
+ "Catalyst::Plugin::Session::State::Cookie version 0.03 or higher is required for this test";
+
+ eval { require Test::WWW::Mechanize::Catalyst }
+ or plan skip_all =>
+ 'Test::WWW::Mechanize::Catalyst is required for this test';
+
+ plan tests => '10';
+
+}
+
+use lib "t/lib";
+use Test::WWW::Mechanize::Catalyst 'FlashTestApp';
+
+my $ua = Test::WWW::Mechanize::Catalyst->new;
+
+# flash absent for initial request
+$ua->get_ok( "http://localhost/first");
+$ua->content_contains( "flash is not set", "not set");
+
+# present for 1st req.
+$ua->get_ok( "http://localhost/second");
+$ua->content_contains( "flash set first time", "set first");
+
+# should be the same 2nd req.
+$ua->get_ok( "http://localhost/third");
+$ua->content_contains( "flash set second time", "set second");
+
+# and the third request, flash->{is_set} has the same value as 2nd.
+$ua->get_ok( "http://localhost/fourth");
+$ua->content_contains( "flash set 3rd time, same val as prev.", "set third");
+
+
+# and should be absent again for the 4th req.
+$ua->get_ok( "http://localhost/fifth");
+$ua->content_contains( "flash is not", "flash has gone");
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/06_finalize.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/06_finalize.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/06_finalize.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,41 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More;
+
+BEGIN {
+ if ( eval { require Catalyst::Plugin::Session::State::Cookie } ) {
+ plan tests => 3;
+ } else {
+ plan skip_all => "Catalyst::Plugin::Session::State::Cookie required";
+ }
+}
+
+my $finalized = 0;
+
+{
+ package TestPlugin;
+ BEGIN { $INC{"TestPlugin.pm"} = 1 } # nasty hack for 5.8.6
+
+ sub finalize_session { $finalized = 1 }
+
+ sub finalize { die "already finalized_session()" if $finalized }
+
+ # Structure inheritance so TestPlugin->finalize() is called *after*
+ # Catalyst::Plugin::Session->finalize()
+ package TestApp;
+
+ use Catalyst qw/
+ Session Session::Store::Dummy Session::State::Cookie +TestPlugin
+ /;
+ __PACKAGE__->setup;
+}
+
+BEGIN { use_ok('Catalyst::Plugin::Session') }
+
+my $c = TestApp->new;
+eval { $c->finalize };
+ok(!$@, "finalize_session() called after all other finalize() methods");
+ok($finalized, "finalize_session() called");
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/99_pod.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/99_pod.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/99_pod.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,7 @@
+use Test::More;
+
+eval "use Test::Pod 1.14";
+plan skip_all => 'Test::Pod 1.14 required' if $@;
+plan skip_all => 'set TEST_POD to enable this test' unless $ENV{TEST_POD};
+
+all_pod_files_ok();
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/99_podcoverage.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/99_podcoverage.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/99_podcoverage.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,7 @@
+use Test::More;
+
+eval "use Test::Pod::Coverage 1.04";
+plan skip_all => 'Test::Pod::Coverage 1.04 required' if $@;
+plan skip_all => 'set TEST_POD to enable this test' unless $ENV{TEST_POD};
+
+all_pod_coverage_ok();
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/lib/FlashTestApp.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/lib/FlashTestApp.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/lib/FlashTestApp.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,61 @@
+#!/usr/bin/perl -w
+
+package FlashTestApp;
+use Catalyst qw/Session Session::Store::Dummy Session::State::Cookie/;
+
+use strict;
+use warnings;
+no warnings 'uninitialized';
+
+sub default : Private {
+ my ($self, $c) = @_;
+ $c->session;
+}
+
+
+sub first : Global {
+ my ( $self, $c ) = @_;
+ if ( ! $c->flash->{is_set}) {
+ $c->stash->{message} = "flash is not set";
+ $c->flash->{is_set} = 1;
+ }
+}
+
+sub second : Global {
+ my ( $self, $c ) = @_;
+ if ($c->flash->{is_set} == 1){
+ $c->stash->{message} = "flash set first time";
+ $c->flash->{is_set}++;
+ }
+}
+
+sub third : Global {
+ my ( $self, $c ) = @_;
+ if ($c->flash->{is_set} == 2) {
+ $c->stash->{message} = "flash set second time";
+ $c->keep_flash("is_set");
+ }
+}
+
+sub fourth : Global {
+ my ( $self, $c ) = @_;
+ if ($c->flash->{is_set} == 2) {
+ $c->stash->{message} = "flash set 3rd time, same val as prev."
+ }
+}
+
+sub fifth : Global {
+ my ( $self, $c ) = @_;
+ $c->forward('/first');
+}
+
+sub end : Private {
+ my ($self, $c) = @_;
+ $c->res->output($c->stash->{message});
+}
+
+
+__PACKAGE__->setup;
+
+__PACKAGE__;
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/lib/SessionTestApp.pm
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/lib/SessionTestApp.pm (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/lib/SessionTestApp.pm 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,36 @@
+#!/usr/bin/perl
+
+package SessionTestApp;
+use Catalyst qw/Session Session::Store::Dummy Session::State::Cookie/;
+
+use strict;
+use warnings;
+
+sub login : Global {
+ my ( $self, $c ) = @_;
+ $c->session;
+ $c->res->output("logged in");
+}
+
+sub logout : Global {
+ my ( $self, $c ) = @_;
+ $c->res->output(
+ "logged out after " . $c->session->{counter} . " requests" );
+ $c->delete_session("logout");
+}
+
+sub page : Global {
+ my ( $self, $c ) = @_;
+ if ( $c->session_is_valid ) {
+ $c->res->output("you are logged in, session expires at " . $c->session_expires);
+ $c->session->{counter}++;
+ }
+ else {
+ $c->res->output("please login");
+ }
+}
+
+__PACKAGE__->setup;
+
+__PACKAGE__;
+
Added: branches/Catalyst-Plugin-Session/flash_in_session/t/live_app.t
===================================================================
--- branches/Catalyst-Plugin-Session/flash_in_session/t/live_app.t (rev 0)
+++ branches/Catalyst-Plugin-Session/flash_in_session/t/live_app.t 2008-12-11 16:42:21 UTC (rev 8828)
@@ -0,0 +1,82 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+
+use Test::More;
+
+BEGIN {
+ eval { require Catalyst::Plugin::Session::State::Cookie; Catalyst::Plugin::Session::State::Cookie->VERSION(0.03) }
+ or plan skip_all =>
+ "Catalyst::Plugin::Session::State::Cookie 0.03 or higher is required for this test";
+
+ eval { require Test::WWW::Mechanize::Catalyst }
+ or plan skip_all =>
+ "Test::WWW::Mechanize::Catalyst is required for this test";
+
+ plan tests => 36;
+}
+
+use lib "t/lib";
+use Test::WWW::Mechanize::Catalyst "SessionTestApp";
+
+my $ua1 = Test::WWW::Mechanize::Catalyst->new;
+my $ua2 = Test::WWW::Mechanize::Catalyst->new;
+
+$_->get_ok( "http://localhost/page", "initial get" ) for $ua1, $ua2;
+
+$ua1->content_contains( "please login", "ua1 not logged in" );
+$ua2->content_contains( "please login", "ua2 not logged in" );
+
+$ua1->get_ok( "http://localhost/login", "log ua1 in" );
+$ua1->content_contains( "logged in", "ua1 logged in" );
+
+$_->get_ok( "http://localhost/page", "get main page" ) for $ua1, $ua2;
+
+$ua1->content_contains( "you are logged in", "ua1 logged in" );
+$ua2->content_contains( "please login", "ua2 not logged in" );
+
+$ua2->get_ok( "http://localhost/login", "get main page" );
+$ua2->content_contains( "logged in", "log ua2 in" );
+
+$_->get_ok( "http://localhost/page", "get main page" ) for $ua1, $ua2;
+
+$ua1->content_contains( "you are logged in", "ua1 logged in" );
+$ua2->content_contains( "you are logged in", "ua2 logged in" );
+
+my ( $u1_expires ) = ($ua1->content =~ /(\d+)$/);
+my ( $u2_expires ) = ($ua2->content =~ /(\d+)$/);
+
+sleep 1;
+
+$_->get_ok( "http://localhost/page", "get main page" ) for $ua1, $ua2;
+
+$ua1->content_contains( "you are logged in", "ua1 logged in" );
+$ua2->content_contains( "you are logged in", "ua2 logged in" );
+
+my ( $u1_expires_updated ) = ($ua1->content =~ /(\d+)$/);
+my ( $u2_expires_updated ) = ($ua2->content =~ /(\d+)$/);
+
+cmp_ok( $u1_expires, "<", $u1_expires_updated, "expiry time updated");
+cmp_ok( $u2_expires, "<", $u2_expires_updated, "expiry time updated");
+
+$ua2->get_ok( "http://localhost/logout", "log ua2 out" );
+$ua2->content_like( qr/logged out/, "ua2 logged out" );
+$ua2->content_like( qr/after 2 request/,
+ "ua2 made 2 requests for page in the session" );
+
+$_->get_ok( "http://localhost/page", "get main page" ) for $ua1, $ua2;
+
+$ua1->content_contains( "you are logged in", "ua1 logged in" );
+$ua2->content_contains( "please login", "ua2 not logged in" );
+
+$ua1->get_ok( "http://localhost/logout", "log ua1 out" );
+$ua1->content_like( qr/logged out/, "ua1 logged out" );
+$ua1->content_like( qr/after 4 requests/,
+ "ua1 made 4 request for page in the session" );
+
+$_->get_ok( "http://localhost/page", "get main page" ) for $ua1, $ua2;
+
+$ua1->content_contains( "please login", "ua1 not logged in" );
+$ua2->content_contains( "please login", "ua2 not logged in" );
+
More information about the Catalyst-commits
mailing list