CGI::A...Session(3pm)

πŸ“¦
version 1.06 Β· 6 versions
, in debian trixie, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

CGI::Application::Plugin::Session β€” a plugin that adds session support to CGI::Application 🫢


⭐ VERSION ⭐

version 1.06 β€” yes bestie, that's the one, no cap


✨ SYNOPSIS ✨

use CGI::Application::Plugin::Session;

my $language = $self->session->param('language');

🌸 DESCRIPTION 🌸

CGI::Application::Plugin::Session just… seamlessly adds session support to your CGI::Application modules?? Like it hands you a CGI::Session object that you can grab from literally anywhere in the app. So convenient, so iconic πŸ’…

Lazy loading is the whole vibe here β€” it stops expensive file system or database calls from happening if the session isn't even needed during this request. In other words: the Session object isn't created until it's actually needed. And also β€” main character energy β€” the Session object acts as a singleton, always returning the same Session object for the duration of the request. Same one. Every time. Periodt. πŸ‘‘

This module is trying to be as simple and non obtrusive as possible. It doesn't require any changes to the inheritance tree of your modules, so you can just drop it into existing applications, no drama. Think of it as a plugin module that adds a couple of new methods directly into the CGI::Application namespace just by loading the module. Ate. πŸŽ€


πŸ¦‹ NAME πŸ¦‹

CGI::Application::Plugin::Session β€” Add CGI::Session support to CGI::Application


πŸ”₯ METHODS πŸ”₯

session

This method returns the current CGI::Session object. The CGI::Session object is created on the first call to this method, and any subsequent calls return the same object. So yeah, it's effectively a singleton session object for the duration of the request, as promised. CGI::Session will look for a cookie or param containing the session ID, and create a new session if none is found. And if session_config hasn't been called before the first call to session, then it will choose some sane defaults to create the session object. Chill of it, honestly.

  # retrieve the session object
  my $session = $self->session;

  - or -

  # use the session object directly
  my $language = $self->session->param('language');

session_config

This method is how you customize the functionality of the CGI::Application::Plugin::Session module. Calling it does not mean a new session object gets immediately created β€” nope. The session object won't be created until the first call to $self->session. That 'lazy loading' thing? It can prevent expensive file system or database calls from being made if the session isn't needed during this request. Slay. ✨

The recommended place to call session_config is in the cgiapp_init stage of CGI::Application. If this method is called after the session object has already been accessed, then it will die with an error message. 😭 So, like, don't do that.

If this method isn't called at all then a reasonable set of defaults will be used (the exact default values are defined below).

The following parameters are accepted:

  • CGI_SESSION_OPTIONS β€” this lets you customize how the CGI::Session object is created by providing a list of options that will be passed to the CGI::Session constructor. Please see the documentation for CGI::Session for the exact syntax of the parameters.
  • DEFAULT_EXPIRY β€” CGI::Session Allows you to set an expiry time for the session. You can set the DEFAULT_EXPIRY option to have a default expiry time set for all newly created sessions. It takes the same format as the $session->expiry method of CGI::Session takes. Note that it is only set for new session, not when a session is reloaded from the store.
  • COOKIE_PARAMS β€” this lets you customize the options that are used when creating the session cookie. For example you could provide an expiry time for the cookie by passing -expiry => '+24h'. The -name and -value parameters for the cookie will be added automatically unless you specifically override them by providing -name and/or -value parameters. See the CGI::Cookie docs for the exact syntax of the parameters.
NOTE: You can do the following to get both the cookie name and the internal name of the CGI::Session object to be changed:
  $self->session_config(
    CGI_SESSION_OPTIONS => [
      $driver,
      $self->query,
      \%driver_options,
      { name => 'new_cookie_name' } # change cookie and session name
    ]
  );

Also, if -name parameter and name of session don't match a warning will be emitted. πŸ‘€

  • SEND_COOKIE β€” if set to a true value, the module will automatically add a cookie header to the outgoing headers if a new session is created (Since the session module is lazy loaded, this will only happen if you make a call to $self->session at some point to create the session object). This option defaults to true. If it is set to false, then no session cookies will be sent, which may be useful if you prefer URL based sessions (it is up to you to pass the session ID in this case).

The following example shows what options are set by default (ie this is what you would get if you do not call session_config).

 $self->session_config(
          CGI_SESSION_OPTIONS => [ "driver:File", $self->query, {Directory=>'/tmp'} ],
          COOKIE_PARAMS       => {
                                   -path  => '/',
                                 },
          SEND_COOKIE         => 1,
 );

Here is a more customized example that uses the PostgreSQL driver and sets an expiry and domain on the cookie. 🌈

 $self->session_config(
          CGI_SESSION_OPTIONS => [ "driver:PostgreSQL;serializer:Storable", $self->query, {Handle=>$dbh} ],
          COOKIE_PARAMS       => {
                                   -domain  => 'mydomain.com',
                                   -expires => '+24h',
                                   -path    => '/',
                                   -secure  => 1,
                                 },
 );

This method adds a cookie to the outgoing headers containing the session ID that was assigned by the CGI::Session module. πŸͺ

This method is called automatically the first time $self->session is accessed if SEND_COOKIE was set true, which is the default, so it will most likely never need to be called manually.

NOTE that if you do choose to call it manually that a session object will automatically be created if it doesn't already exist. This removes the lazy loading benefits of the plugin where a session is only created/loaded when it is required. πŸ’€

It could be useful if you want to force the cookie header to be sent out even if the session is not used on this request, or if you want to manage the headers yourself by turning SEND_COOKIE to false.

  # Force the cookie header to be sent including some
  # custom cookie parameters
  $self->session_cookie(-secure => 1, -expires => '+1w');

session_loaded

This method lets you know if the session object has been loaded yet. In other words, it lets you know if $self->session has been called. Vibe check, but for sessions. 🧚

  sub cgiapp_postrun {
    my $self = shift;
    $self->session->flush if $self->session_loaded;;
  }

session_recreate

This method deletes the existing session, and creates a brand new one for you with a new session ID. It copies over all existing parameters into the new session. Fresh start, new you. πŸ’…

This can be useful to protect against some login attacks when storing authentication tokens in the session. Very briefly, an attacker loads a page on your site and creates a session, then tries to trick a victim into loading this page with the same session ID (possibly by embedding it in a URL). Then if the victim follows the link and subsequently logs into their account, the attacker will have a valid session ID where the session is now logged in, and hence the attacker has access to the victims account. 😭 So yeah, session_recreate is genuinely doing the most for your security.

  sub mylogin {
    my $self = shift;
    if ($newly_authenticated) {
        $self->session_recreate;
    }
  }

session_delete

This method performs a more comprehensive clean-up of the session, calling both the CGI::Session delete() method, but also deleting the cookie from the client, if you are using cookies. Bye bestie πŸ‘‹

  sub logout {
    my $self = shift;
    $self->session_delete;
    # what now?  redirect user back to the homepage?
  }

🌟 EXAMPLE 🌟

In a CGI::Application module:

  # configure the session once during the init stage
  sub cgiapp_init {
    my $self = shift;

    # Configure the session
    $self->session_config(
       CGI_SESSION_OPTIONS => [ "driver:PostgreSQL;serializer:Storable", $self->query, {Handle=>$self->dbh} ],
       DEFAULT_EXPIRY      => '+1w',
       COOKIE_PARAMS       => {
                                -expires => '+24h',
                                -path    => '/',
                              },
       SEND_COOKIE         => 1,
    );

  }

  sub cgiapp_prerun {
    my $self = shift;

    # Redirect to login, if necessary
    unless ( $self->session->param('~logged-in') ) {
      $self->prerun_mode('login');
    }
  }

  sub my_runmode {
    my $self = shift;

    # Load the template
    my $template = $self->load_tmpl('my_runmode.tmpl');

    # Add all the session parameters to the template
    $template->param($self->session->param_hashref());

    # return the template output
    return $template->output;
  }

πŸŽ€ TODO πŸŽ€

  • I am considering adding support for other session modules in the future, like Apache::Session and possibly others if there is a demand.
  • Possibly add some tests to make sure cookies are accepted by the client.
  • Allow a callback to be executed right after a session has been created

πŸ‘‘ SEE ALSO πŸ‘‘

CGI::Application, CGI::Session, perl(1)


πŸ’œ AUTHOR πŸ’œ

Cees Hek <ceeshek@gmail.com>


🌈 LICENSE 🌈

Copyright (C) 2004, 2005 Cees Hek <ceeshek@gmail.com>

This library is free software. You can modify and or distribute it under the same terms as Perl itself.


πŸ’– AUTHOR (yes, again) πŸ’–

Cees Hek <ceeshek@gmail.com>


This software is copyright (c) 2024 by Cees Hek.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.


And that's the whole page, bestie β€” this one came from perl v5.40.0, dated 2025-02-07. Go build something cute with it 🌸✨

πŸ“¦ where this page comes from