如何设置由Plack :: Middleware :: Session管理的cookie的到期时间?

时间:2015-03-21 20:09:56

标签: perl session session-cookies middleware plack

现在我的app.psgi包含(简化):

builder {
      enable 'Session', store => 'File'; #default uses Plack::Session::State::Cookie
      $app;
};

稍后,在$app我使用:

my $req = Plack::Request->new($env);
my $session = $req->session(); #returns env->{'psgix.session'}
$session->{user} = "name";

它可以确定,例如:

  • 当用户登录时,我将他的名字存储在服​​务器端存储的会话文件中,Plack::Middleware::Session设置一个简单的会话状态cookie,
  • 当用户关闭浏览器时,Cookie会自动清除(因为默认情况下Plack::Session::State::Cookie并未设置Cookie的任何到期时间。)

现在,我希望实施"记住我"我的登录面板中的功能。在这种情况下,不应从浏览器中自动删除sesion-state-cookie。可以使用Plack::Session::State::Cookie中的expires方法完成此操作。

问题:

如何从$app更改Cookie过期(由Session中间件管理)。换句话说,如何在这里稍微调用expire方法:

my $req = Plack::Request->new($env);
my $session = $req->session(); #returns env->{'psgix.session'}
$session->{user} = "name";
my $cookie_state = WHAT_TO_DO_HERE_TO_GET; #the current Plack::Session::State::Cookie object
$cookie_state->expire(86400*14); #expire in two weeks

如果有人需要,这是一个有效的例子。

use strict;
use warnings;
use Plack::Request;
use Plack::Response;
use Plack::Builder;
use Data::Dumper;

my $app = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $req->session;
    my $res = Plack::Response->new(200);
    $res->content_type('text/html');
    my $link = $session->{user}
            ? q{ <a href="/logout">logout</a>}
            : q{ <a href="/login">login</a>}
            ;
    $res->body(["Session user:", $session->{user}, "<br>$link"]);
    return $res->finalize;
};

my $login = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $req->session;

    $session->{user} = "some";
    #how to set here the session-state-cookie expiration?

    my $res = Plack::Response->new();
    $res->redirect("/", 302);
    return $res->finalize;
};

my $logout = sub {
    my $env = shift;
    my $req = Plack::Request->new($env);
    my $session = $req->session;
    delete $session->{user};
    my $res = Plack::Response->new();
    $res->redirect("/", 302);
    return $res->finalize;
};

builder {
    enable 'Session', store => 'File';
    mount "/login" => $login; 
    mount "/logout" => $logout; 
    mount "/favicon.ico" => sub { return [ 404, ['Content-Type' => 'text/html'], [ '404 Not Found' ] ] };
    mount "/" => $app; 
};

1 个答案:

答案 0 :(得分:5)

您无法直接更改到期日期,但您可以强制会话中间件创建一个新的会话,其新的到期日期如下:

$env->{'psgix.session.options'}{change_id} = 1;
$env->{'psgix.session.options'}{expires}   = $my_expires;

如果用户登录,您应该始终将ID更改为prevent session fixation attacks。有关支持的到期日期格式,请参阅Cookie::Baker

编辑:如果要全局设置默认过期超时,可以手动构建状态对象并将expires参数传递给构造函数:

builder {
    enable 'Session',
        state => Plack::Session::State->new(
            expires => $timeout_in_seconds,
        );
    $app;
};