518d8077c1f5a3100e99619e02fc09370186317c
[catagits/Catalyst-Plugin-Session-State-Cookie.git] / lib / Catalyst / Plugin / Session / State / Cookie.pm
1 package Catalyst::Plugin::Session::State::Cookie;
2 use base qw/Catalyst::Plugin::Session::State/;
3
4 use strict;
5 use warnings;
6
7 use NEXT;
8
9 our $VERSION = "0.01";
10
11 sub setup_session {
12         my $c = shift;
13
14         $c->NEXT::setup_session(@_);
15
16         $c->config->{session}{cookie_name} ||= "session";
17 }
18
19 sub finalize {
20     my $c = shift;
21
22         my $cookie_name = $c->config->{session}{cookie_name};
23
24     if ( my $sid = $c->sessionid ) {
25         my $cookie = $c->request->cookies->{$cookie_name};
26         if ( !$cookie or $cookie->value ne $sid ) {
27             $c->response->cookies->{$cookie_name} = { value => $sid };
28             $c->log->debug(qq/A cookie with the session id "$sid" was saved/)
29               if $c->debug;
30         }
31     }
32
33     return $c->NEXT::finalize(@_);
34 }
35
36 sub prepare_cookies {
37     my $c = shift;
38
39     my $ret = $c->NEXT::prepare_cookies(@_);
40
41         my $cookie_name = $c->config->{session}{cookie_name};
42
43     if ( my $cookie = $c->request->cookies->{$cookie_name} ) {
44         my $sid = $cookie->value;
45         $c->sessionid($sid);
46         $c->log->debug(qq/Found sessionid "$sid" in cookie/) if $c->debug;
47     }
48
49         return $ret;
50 }
51
52 __PACKAGE__
53
54 __END__
55
56 =pod
57
58 =head1 NAME
59
60 Catalyst::Plugin::Session::State::Cookie - A session ID 
61
62 =head1 SYNOPSIS
63
64         use Catalyst qw/Session Session::State::Cookie Session::Store::Foo/;
65
66 =head1 DESCRIPTION
67
68 In order for L<Catalyst::Plugin::Session> to work the session ID needs to be
69 stored on the client, and the session data needs to be stored on the server.
70
71 This plugin stores the session ID on the client using the cookie mechanism.
72
73 =head1 EXTENDED METHODS
74
75 =over 4
76
77 =item prepare_cookies
78
79 Will restore if an appropriate cookie is found.
80
81 =item finalize
82
83 Will set a cookie called C<session> if it doesn't exist or if it's value is not the current session id.
84
85 =back
86
87 =head1 CONFIGURATION
88
89 =over 4
90
91 =item cookie_name
92
93 The name of the cookie to store (defaults to C<session>).
94
95 =back
96
97 =head1 SEE ALSO
98
99 L<Catalyst>, L<Catalyst::Plugin::Session>.
100
101 =head1 AUTHOR
102
103 Sebastian Riedel E<lt>C<sri@cpan.org>E<gt>,
104 Marcus Ramberg E<lt>C<mramberg@cpan.org>E<gt>,
105 Andrew Ford E<lt>C<andrewf@cpan.org>E<gt>,
106 Yuval Kogman E<lt>C<nothingmuch@woobling.org>E<gt>
107
108 =head1 COPYRIGHT
109
110 This program is free software, you can redistribute it and/or modify it
111 under the same terms as Perl itself.
112
113 =cut
114
115 1;