1

Whatever expiration value that I give to expires() or expires_delta(), the cookie expiration is always one hour. How do I change it so that the session and the cookie expiration times match?

Moritz Bunkus
  • 11,592
  • 3
  • 37
  • 49
Jeff Jirsa
  • 11
  • 1

1 Answers1

3

Although I like vti's work, that distribution looks outdated and was replaced in the past. Today the standard way to set session expire dates is explained in Mojolicious::Sessions:

default_expiration

my $time  = $sessions->default_expiration;
$sessions = $sessions->default_expiration(3600);

Default time for sessions to expire in seconds from now, defaults to 3600. The expiration timeout gets refreshed for every request. Setting the value to 0 will allow sessions to persist until the browser window is closed, this can have security implications though. For more control you can also use the expiration and expires session values.

# Expiration date in epoch seconds from now (persists between requests)
$c->session(expiration => 604800);

# Expiration date as absolute epoch time (only valid for one request)
$c->session(expires => time + 604800);

# Delete whole session by setting an expiration date in the past
$c->session(expires => 1);

I wrote a small test script to make sure it works:

#!/usr/bin/env perl

use Mojolicious::Lite;
use Time::Local 'timegm';

# set some session variable
get '/test' => sub {
    my $self = shift;
    $self->session(
        expires => timegm(0, 0, 0, 4, 4, 142), # star wars day '42
        foo     => 42,
    );
    $self->render_text('foo is set');
};

use Test::More;
use Test::Mojo;
use Mojo::Cookie::Response;
my $t = Test::Mojo->new;

$t->get_ok('/test')->status_is(200)->content_is('foo is set');
my $cookies = Mojo::Cookie::Response->parse($t->tx->res->headers->set_cookie);
is $cookies->[0]->expires, 'Sun, 04 May 2042 00:00:00 GMT', 'right expire time';

done_testing;

Output:

ok 1 - get /test
ok 2 - 200 OK
ok 3 - exact match for content
ok 4 - right expire time
1..4
memowe
  • 2,656
  • 16
  • 25