ASP4

 view release on metacpan or  search on metacpan

lib/ASP4/SessionStateManager.pm  view on Meta::CPAN


package ASP4::SessionStateManager;

use strict;
use warnings 'all';
use base 'Ima::DBI::Contextual';
use HTTP::Date qw( time2iso time2str str2time );
use Time::HiRes 'gettimeofday';
use Digest::MD5 'md5_hex';
use Storable qw( freeze thaw );
use Scalar::Util 'weaken';
use ASP4::ConfigLoader;


sub new
{
  my ($class, $r) = @_;
  my $s = bless { }, $class;
  my $conn = context()->config->data_connections->session;
  
  local $^W = 0;
  $class->set_db('Session',
    $conn->dsn,
    $conn->username,
    $conn->password
  );
  
  my $id = $s->parse_session_id();
  unless( $id && $s->verify_session_id( $id, $conn->session_timeout ) )
  {
    $s->{SessionID} = $s->new_session_id();
    $s->write_session_cookie($r);
    return $s->create( $s->{SessionID} );
  }# end unless()
  
  return $s->retrieve( $id );
}# end new()

sub context { ASP4::HTTPContext->current }

sub is_read_only
{
  my ($s, $val) = @_;
  
  if( defined($val) )
  {
    $s->{____is_read_only} = $val;
  }
  else
  {
    return $s->{____is_read_only};
  }# end if()
}# end is_readonly()


sub parse_session_id
{
  my $session_config = context()->config->data_connections->session;
  my $cookie_name = $session_config->cookie_name;
  my ($id) = ($ENV{HTTP_COOKIE}||'') =~ m/\b\Q$cookie_name\E\=([a-f0-9]{32,32})/s;

  return $id;
}# end parse_session_id()


sub new_session_id { md5_hex( join ':', ( context()->config->web->www_root, $$, gettimeofday() ) ) }


sub write_session_cookie
{
  my ($s, $r) = @_;
  
  my $config = context()->config->data_connections->session;
  my $domain = "";
  unless( $config->cookie_domain eq '*' )
  {
    $domain = "domain=" . ( $config->cookie_domain || $ENV{HTTP_HOST} ) . ";";
  }# end unless()
  my $name = $config->cookie_name;
  
  my @cookie = (
    'Set-Cookie' => "$name=$s->{SessionID}; path=/; $domain"
  );
  context()->headers_out->push_header( @cookie );
  @cookie;



( run in 2.225 seconds using v1.01-cache-2.11-cpan-39bf76dae61 )