Thomas L. Shinnick

NAME

Catalyst::Plugin::Session::CGISession - use CGI::Session for persistent session data

VERSION

This document describes Catalyst::Plugin::Session::CGISession version 0.0.1

SYNOPSIS

    use Catalyst  qw{ ... Session::CGISession ... };

    MyApp->config->{session} = {
        expires   => 3600,
        rewrite   => 1,
    };

    $c->session->{user_email} = 'quibble@dibble.edu';

    # Later, in another following request:

    $smtp->to( $c->session->{user_email} );

DESCRIPTION

This plugin provides the same functionality as the original Session::FastMmap plugin but uses the CGI::Session module for the session data management.

The motivations to develop this plugin were:

  • provide better session data expiration handling, as is available through the CGI::Session module

  • provide an easier migration to Catalyst for applications that have been using CGI::Session and its param() and other methods

  • allow Windows users to avoid the workarounds needed to make Cache::FastMmap work

The difference in session expiration between this plugin and Session::FastMmap is small but important. CGI::Session resets the expiration time limit on every access to the session. A one day time limit means the session data disappears 24 hours after the last request using that session. With Session::FastMmap the limit would be 24 hours after the first request, when the session is created.

While this plugin adds some functions and methods beyond those available with Session::FastMmap, new development most likely should avoid using these features. Try to use only the common feature, session(), to stay compatible with Session::FastMmap and other future session plugins.

INTERFACE

PUBLIC METHODS

session

Returns a hash reference that the caller can use to store persistent data items. Everything stored into this hash will be saved to storage when a request completes. Upon the next request with the same session id the saved data will again be available through this method.

This method performs the same functions as Session::FastMmap::session.

uri

Extends an uri with session id if needed. This is used when the {rewrite} configuration option is enabled.

    my $uri = $c->uri('http://localhost/foo');

This method performs the same functions as Session::FastMmap::uri.

EXPOSED CGI::SESSION METHODS

Applications might require some of the specialized features of CGI:Session. A small number of CGI::Session methods are exposed through this plugin.

session_param

A single session data hash may be too restrictive for some applications. In particular, some applications may want to expire individual data items separately, as is allowed by CGI::Session. See the CGI::Session param() method documentation for more details.

session_expire

Setting a data item-specific expiration time is done with the CGI::Session expire() method. Please see that documentation for details.

session_is_new

It may be useful for applications to know when a session is newly created and not a continuation of a previous session. This is usually detectable by checking for missing previous values. But if an application really has to know, the CGI::Session is_new() method will tell you. Please see that documentation for details.

session_flush

The persistent session data hash is written to backing storage at the end of every request. If for some reason an application needs to force an update early, this method will call the CGI::Session flush() method.

session_delete

Calls the CGI:Session delete() method which marks the session as "to be deleted." Note that the session data is not actually deleted from storage until the current request finishes, or if you explicitly call session_flush().

session_dump

session_dump_at_close

CGI::Session provides a dump() method as a convenience during testing. This plugin extends that method to dump a varying amount of data and also postponing the request, dumping the data at end of request into the debug log.

session_dump() will immediately return a string of formatted dump data. session_dump_at_close() will wait until end of request processing and then dump the session data into the debug log just before the data is written to backing storage.

You may specify how much data to dump using a single number value:

  • =1 dump the session data hash returned by session()

  • =2 dump the whole CGI::Session parameters hash, including parameters set using session_param()

  • =3 dump the entire CGI::Session object

    my $dumped_hash_string = $c->session_dump(1);

will return a string containing the Data::Dumper formatted dump of the session hash.

    $c->session_dump_at_close(2);

specifies that at end of request processing, the usual session data hash and also any other parameters should be displayed in the Catalyst debug log.

EXTENDED CATALYST METHODS

setup

Check session-related configuration values and default those not set from the configuration.

prepare_action

This method attempts to determine the session id for the current request in two different ways.

First it checks whether a session id has been embedded within the request URL path. This is signaled by the sequence '/-/' followed by a session id. If this is found then the request path is truncated to only the part preceding the session id marker '/-/'. The part following the marker is used to set $c->sessionid()

The second method is to check for a cookie with the name 'session' sent in the request. If found then the cookie value is used to set $c->sessionid().

If a session id is found by both methods the value from the cookie will be used.

finalize

This method is called as part of the end of request processing chain.

If session data has been created or read then this method is responsible for writing session data out to backing storage.

If the rewrite configuration option is enabled then URI rewriting is also performed on body text and any redirect URL.

CONFIGURATION AND ENVIRONMENT

Session::CGISession uses configuration options as found in $c->config->{session} data.

CONFIG OPTIONS FOR MODULE

expires

How many seconds until the session expires. The default is 24 hours.

Note that the underlying CGI::Session handler resets the session expiration time upon every access. Thus a session will not normally expire until this many seconds have elapsed since the last access to the session. This is a useful difference from the Session::FastMmap plugin which sets the expiration time of a session only once at session creation.

rewrite

One method for remembering the current session id value from one request to the next is to embed the session id into every request URL. If the user has disabled cookies in their browser this is the only way to pass session id from one request to another.

When this option is enabled the module will attempt to add the session id to every URL in the response output. In addition it will update a redirect URL when redirect is used.

See method uri()

This configuration option requests the same feature as Session::FastMmap provides.

CONFIG OPTIONS FOR COOKIES

how many seconds until the session cookie expires at the client browser. See expires option in CGI::Cookie for format. default is the expires option described above. This option will override the default when specified.

Domain set in the session cookie. See domain option in CGI::Cookie for format. default is none.

Path set in the session cookie. See path option in CGI::Cookie for format. default is none.

Secure flag set in the session cookie. See secure option in CGI::Cookie for format. default is none.

CONFIG OPTIONS FOR CGI::SESSION

You may want to explicitly control how and where CGI::Session stores session data files. While this module provides defaults for parameters to CGI::Session, your needs may require specific values.

You may specify values to be given directly to the CGI::Session new() method using the cgis_dsn and cgis_options configuration parameters.

cgis_dsn

This option value becomes the first argument to the CGI::Session new() call, $dsn or Data Source Name. This parameter can configure the backing storage type, the method for serializing data, and the method for creating session id values. It is a combination of one, two or three specifications.

The default value used by this module is:

    $c->config->{session}->{cgis_dsn}
            = 'driver:File;serializer:Storable;id:MD5';

cgis_options

Some of the driver, serializer and id generation modules used with CGI::Session can be given additional parameters to control how they work. One obvious example is telling the plain file driver what directory to use when storing session files.

You may use this hash value to supply these additional parameters, given to CGI::Session new() as the third argument. These are named parameters and so you must use a hash reference. An example in code would be:

    $c->config->{session}->{cgis_options}
            = {
                DataSource  => 'dbi:mysql:database=warren;host=rabitton',
                User        => 'flopsie',
                Password    => 'furryface',
              };

An example in the form of a section from a YAML file would be:

    session:
        cgis_dsn: driver:mysql;serializer:Storable;id:MD5
        cgis_options:
            DataSource: dbi:mysql:database=warren;host=rabitton
            User: flopsie
            Password: furryface

Details about the various parameters for drivers and id generation modules can be found in the CGI::Session documentation.

Database driver modules support the following parameters:

  DataSource - the DSN value given to DBI->connect()

  Handle     - a DBI database handle object ($dbh), if already connected

  TableName  - name of the table where session data will be stored

  User       - user privileged to connect to the database defined in DataSource

  Password   - password of the same user

Individual drivers support other parameters, such as:

  file          Directory     where session files will be stored

  db_file       FileName      location of the Berkely DB file

  postgresql    ColumnType    value 'binary' might be needed

The default value used by this module (to match the above default for cgis_dsn) is:

    $c->config->{session}->{cgis_options}
            = {
                Directory => File::Spec->tmpdir()
              };

SPECIALIZED OPTIONS FOR CGI::SESSION

CGI::Session has some settings which are not easily specified using the available API calls. Unfortunately a number of these can be set only by storing into global variables.

If you need to change the default values of these CGI::Session settings you will have to manage to do this in your code, before this plugin module is called by the MyApp->setup() call.

An example will illustrate this. Suppose that the default values for cgis_dsn and cgis_dsn are satisfactory, but you want to change the naming of session files created by the default CGI::Session File driver. That driver's default for filenames is 'cgisess_%s' and you would rather use 'myapp_%s.ses'.

    use CGI::Session::Driver::file;
    use Catalyst  qw{ ... Session::CGISession ... };

    __PACKAGE__->config->{session} = {
        expires   => 7 * 24 * 60 * 60,
        rewrite   => 1,
    };

    $CGI::Session::Driver::file::FileName = 'myapp_%s.ses';

    __PACKAGE__->setup();

The plugin module is not initialized until the call to setup(). Any prior modifications to the defaults of CGI::Session will be available to the plugin.

If you are using CGI::Session 3.x you would have to code:

    use CGI::Session::File;

    $CGI::Session::Driver::FileName = 'myapp_%s.ses';

DIAGNOSTICS

There are conditions where CGI::Session will be unable to create a session object. The most likely causes are misconfigured options or unavailable modules.

When CGI::Session returns an error the error message will be repeated in the Catalyst error log. Below is an example error message resulting from a misspelled name in the cgis_dsn configuration parameter:

  [Thu ... 2005] [catalyst] [e]
    Unable to create CGI::Session object, error:
      'new(): failed: couldn't load CGI::Session::Serialize::storrable:
          Can't locate CGI/Session/Serialize/storrable.pm in @INC

Please note that CGI::Session 3.x DSN names are case-sensitive. While "driver:mysql" works under CGIS 4.x, it must be "driver:MySQL" when using CGIS 3.x.

DEPENDENCIES

This module was developed using the first CGI::Session 4.00 release. It was subsequently tested under 3.95, the last 3.x version.

Testing has been done using:

    Windows XP

        CGI::Session 4.00   'File' driver

        CGI::Session 4.00   MySQL 3.23.x

        CGI::Session 3.95   MySQL 3.23.x
            Note: driver name case sensitivity, e.g.
                cgis_dsn: driver:MySQL;serializer:Storable;id:MD5
            Note: TableName not available, must use global variable, e.g.
                $CGI::Session::MySQL::TABLE_NAME = 'myapp_sessions';

        CGI::Session 3.95   'File' driver
            Note: different global variable $CGI::Session::File::FileName

    Linux

        CGI::Session 3.95   'File' driver
            Note: this driver leaves session data tainted

        CGI::Session 3.95   MySQL 3.23.x

INCOMPATIBILITIES

None reported.

BUGS AND LIMITATIONS

No bugs have yet been reported.

Please report any bugs or feature requests to bug-catalyst-plugin-session-cgisession@rt.cpan.org, or through the web interface at http://rt.cpan.org.

Catalyst Plugin Module Order

Other Catalyst plugin modules may rely upon session data in order to correctly initialize themselves. This may require some care in the order that plugin modules are named to Catalyst.

For instance, the C::P::Authentication::CDBI module expects to find $c->session->{user} and $c->session->{user_id} from any previous session for logged-in users.

Thus when defining the order of plugins you should take care that the session modules like C::P::Session::CGISession are loaded before any module that might need session data.

    use Catalyst qw{    ...
                     Session::CGISession
                     Authentication::CDBI
                        ...
                   };

SEE ALSO

Catalyst
Catalyst::Plugin::Session::FastMmap
Catalyst::Plugin::Session::Flex
CGI::Session
CGI::Cookie

THANKS

To Christian Hansen, from whose test program implementation of CGI::Session use I borrowed extensively,

To Andy Grundman, for the solution to poking cookie values,

To Sebastian Riedel and Marcus Ramberg, for the Catalyst::Plugin::Session::FastMmap module used to get me started,

And to them and the rest of the contributors to Catalyst, for a great start!

AUTHOR

Thomas L. Shinnick <tshinnic@cpan.org>

LICENCE AND COPYRIGHT

Copyright (c) 2005, Thomas L. Shinnick <tshinnic@cpan.org>. All rights reserved.

This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.

DISCLAIMER OF WARRANTY

BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION.

IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.

2 POD Errors

The following errors were encountered while parsing the POD:

Around line 786:

L<> starts or ends with whitespace

Around line 788:

L<> starts or ends with whitespace




Hosting generously
sponsored by Bytemark