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