blib/lib/PEF/Front/Session.pm untested

filter: Statementstmt 0.0% 0 / 67 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 17 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 12 totaltotal 0.0% 0 / 126 SCAR 37.4
CC
6
Cov
0%
new
12.0
load
6.0
data
6.0
CRAP 42.0
1 package PEF::Front::Session;
2  
3 use strict;
4 use warnings;
5 use PEF::Front::Config;
6 use MLDBM::Sync;
7 use MLDBM qw(GDBM_File Storable);
8 use Fcntl qw(:DEFAULT :flock);
9 use Digest::SHA qw(sha1_hex);
10 use Scalar::Util 'blessed';
11  
12 sub _secure_value {
13 open my $urand, '<', '/dev/urandom' or die "can't open /dev/urandom: $!";
14 read ($urand, my $buf, 32);
15 close $urand;
16 return sha1_hex($buf);
17 }
18  
19 sub _key () { 0 }
20 sub _session () { 1 }
21 sub _expires () { 0 }
22 sub _data () { 1 }
23  
24 sub new {
25 my ($class, $request) = @_;
26 my $key = (
27 blessed($request) ? $request->param(cfg_session_request_field())
28 || $request->cookies->{cfg_session_request_field()}
29 : ref ($request) ? $request->{cfg_session_request_field()}
30 : $request
31 );
32 $key ||= _secure_value;
33 my $self = bless [$key, [time + cfg_session_ttl, {}]], $class;
34 $self->load;
35 $self;
36 }
37  
38 sub load {
39 my $self = $_[0];
40 my %session_db;
41 my $sobj = tie (%session_db, 'MLDBM::Sync', cfg_session_db_file, O_CREAT | O_RDWR, 0660) or die "$!";
42 $sobj->Lock;
43 my $session = $session_db{$self->[_key]};
44 if ($session && $session->[_expires] > time) {
45 $self->[_session] = $session;
46 $session->[_expires] = time + cfg_session_ttl;
47 } else {
48 delete $session_db{$self->[_key]};
49 }
50 $sobj->UnLock;
51 }
52  
53 sub store {
54 my $self = $_[0];
55 tie (my %session_db, 'MLDBM::Sync', cfg_session_db_file, O_CREAT | O_RDWR, 0660) or die "$!";
56 $self->[_session][_expires] = time + cfg_session_ttl;
57 $session_db{$self->[_key]} = $self->[_session];
58 }
59  
60 sub destroy {
61 my $self = $_[0];
62 $self->[_session][_expires] = 0;
63 tie (my %session_db, 'MLDBM::Sync', cfg_session_db_file, O_CREAT | O_RDWR, 0660) or die "$!";
64 delete $session_db{$self->[_key]};
65 }
66  
67 sub data {
68 my ($self, $data) = @_;
69 if (defined ($data)) {
70 $self->[_session][_data] = $data;
71 }
72 $self->[_session][_data];
73 }
74  
75 sub key {
76 my ($self) = @_;
77 $self->[_key];
78 }
79  
80 sub DESTROY {
81 my $self = $_[0];
82 if ($self->[_session][_expires] > time) {
83 $self->store;
84 } else {
85 $self->destroy;
86 }
87 }
88  
89 1;
90  
91 __END__