Added high performance version of the Sessions code as a branch
[catagits/Catalyst-Plugin-Session.git] / lib / Catalyst / Plugin / SessionHP / State / Cookie.pm
1 package Catalyst::Plugin::SessionHP::State::Cookie;
2 use base qw/Catalyst::Plugin::SessionHP::State Class::Accessor::Fast/;
3
4 use strict;
5 use warnings;
6
7 use MRO::Compat;
8 use Catalyst::Utils ();
9
10 our $VERSION = "0.10";
11
12 BEGIN { __PACKAGE__->mk_accessors(qw/_deleted_session_id/) }
13
14 sub setup_session {
15     my $c = shift;
16
17     $c->maybe::next::method(@_);
18
19     $c->config->{session}{cookie_name}
20         ||= Catalyst::Utils::appprefix($c) . '_session';
21
22 }
23
24 sub _session_cookie_name {
25     my $c = shift;
26     return $c->config->{session}{cookie_name};
27 }
28
29 sub finalize_session {
30     my $c = shift;
31
32     # we want to run after the other finalizing has been done
33     $c->maybe::next::method(@_);
34
35     # If there is no session_id then we should not do anything
36     return unless $c->_session_id;
37
38     # create the cookie
39     my $cookie = { value => $c->_session_id, };
40
41     # set the expriation time
42     # get the cookie expiry time and add a little buffer for testing
43     unless ( $c->session->{__session_limit_to_this_visit} ) {
44         $cookie->{expires} = $c->_session_expiry_time + 60;
45     }
46
47     $cookie->{secure} = 1 if $c->config->{session}{cookie_secure};
48
49     # add the cookie to the headers
50     $c->response->cookies->{ $c->_session_cookie_name } = $cookie;
51
52     # Also ensure that at the least the cookie is not cached. Other caching is
53     # upto the app to implement. Don't apply to secure connections as it leads
54     # to a bug where IE will not download files.
55     # (http://support.microsoft.com/kb/812935/en-us)
56     $c->response->header( 'Cache-control' => 'no-cache="set-cookie"' )
57         unless $c->req->secure;
58 }
59
60 sub get_sesson_id_from_state {
61     my $c = shift;
62
63     # get _request_ cookie
64     my $cookie = $c->request->cookies->{ $c->_session_cookie_name };
65
66     if ($cookie) {
67         my $sid = $cookie->value;
68         $c->log->debug(qq/Found sessionid "$sid" in cookie/) if $c->debug;
69         return $sid if $sid;
70     }
71
72     # If we could not find the id pass on to the next state
73     $c->maybe::next::method(@_);
74 }
75
76 sub delete_session {
77     my ( $c, $msg ) = @_;
78
79     # create the cookie
80     my $cookie = {
81         value   => '',
82         expires => 0,
83     };
84     $cookie->{secure} = 1 if $c->config->{session}{cookie_secure};
85
86     # add the cookie to the headers
87     $c->response->cookies->{ $c->_session_cookie_name } = $cookie;
88
89     $c->maybe::next::method($msg);
90 }
91
92 1;