App-ZofCMS
view release on metacpan or search on metacpan
lib/App/ZofCMS/Plugin/Session.pm view on Meta::CPAN
#dsn => "DBI:mysql:database=test;host=localhost",
user => 'root',
pass => undef,
opt => { RaiseError => 1, AutoCommit => 1 },
table => 'session',
create_table => 0,
cookie_name => 'plug_session_id',
cookie_expiry => '+24h',
auto => 1,
cell => 'd',
key => 'session',
no_op => 0,
no_load => 0,
no_save => 0,
session_expiry => 86400, # 24 hours
%{ $config->conf->{plug_session} || {} },
%{ $template->{plug_session} || {} },
);
return
if $conf{no_op};
my $dbh = DBI->connect_cached(
@conf{ qw/dsn user pass opt/ }
);
if ( $conf{create_table} ) {
$dbh->do(
"CREATE TABLE `$conf{table}` (
`id` TEXT,
`time` VARCHAR(10),
`data` TEXT
);",
);
}
my $session_id = $config->cgi->cookie( $conf{cookie_name} );
if ( $conf{auto} ) {
$template->{plug_session} = \%conf;
if ( defined $template->{d}{session} ) {
if ( defined $session_id ) {
$dbh->do(
"UPDATE $conf{table} SET data = ?, time = ? WHERE id = ?",
undef,
freeze( $template->{d}{session} ),
time(),
$session_id,
);
}
else {
$session_id = rand() . time() . rand();
$session_id =~ tr/.//d;
my $cookie = $config->cgi->cookie(
-name => $conf{cookie_name},
-path => '/',
-value => $session_id,
-expires => $conf{cookie_expiry},
);
print "Set-Cookie: $cookie\n";
$dbh->do(
"INSERT INTO $conf{table} VALUES( ?, ?, ? );",
undef,
$session_id,
time(),
freeze( $template->{ $conf{cell} }{ $conf{key} } ),
);
}
$dbh->do(
"DELETE FROM $conf{table} WHERE time < ?",
undef,
time() - $conf{session_expiry},
);
}
elsif ( defined $session_id ) {
my $session = $dbh->selectall_arrayref(
"SELECT * FROM $conf{table} WHERE id = ?",
{ Slice => {} },
$session_id,
) || [];
@$session
and $template->{ $conf{cell} }{ $conf{key} } = thaw $session->[0]{data};
}
}
}
1;
__END__
=encoding utf8
=head1 NAME
App::ZofCMS::Plugin::Session - plugin for storing data across requests
=head1 SYNOPSIS
plugins => [
{ Session => 2000 },
{ Sub => 3000 },
],
plugins2 => [
qw/Session/,
],
plug_session => {
dsn => "DBI:mysql:database=test;host=localhost",
user => 'test',
pass => 'test',
},
plug_sub => sub {
my $t = shift;
$t->{d}{session}{time} = localtime;
},
( run in 0.550 second using v1.01-cache-2.11-cpan-39bf76dae61 )