Skip to content

Commit

Permalink
added deserialize and serialize callbacks to Mojolicious::Sessions
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Jun 11, 2014
1 parent 555108c commit 563a2c7
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
1 change: 1 addition & 0 deletions Changes
@@ -1,5 +1,6 @@

5.06 2014-06-11
- Added deserialize and serialize attributes to Mojolicious::Sessions.
- Improved redirect_to to behave more like url_for.
- Fixed bug in Mojo::UserAgent where HTTP/1.0 connections were sometimes
kept alive.
Expand Down
33 changes: 30 additions & 3 deletions lib/Mojolicious/Sessions.pm
@@ -1,20 +1,22 @@
package Mojolicious::Sessions;
use Mojo::Base -base;

use Mojo::JSON qw(encode_json j);
use Mojo::JSON;
use Mojo::Util qw(b64_decode b64_encode);

has [qw(cookie_domain secure)];
has cookie_name => 'mojolicious';
has cookie_path => '/';
has default_expiration => 3600;
has deserialize => sub { \&Mojo::JSON::j };
has serialize => sub { \&Mojo::JSON::encode_json };

sub load {
my ($self, $c) = @_;

return unless my $value = $c->signed_cookie($self->cookie_name);
$value =~ y/-/=/;
return unless my $session = j(b64_decode $value);
return unless my $session = $self->deserialize->(b64_decode $value);

# "expiration" value is inherited
my $expiration = $session->{expiration} // $self->default_expiration;
Expand Down Expand Up @@ -46,7 +48,7 @@ sub store {
$session->{expires} = $default || time + $expiration
if $expiration || $default;

my $value = b64_encode(encode_json($session), '');
my $value = b64_encode($self->serialize->($session), '');
$value =~ y/=/-/;
my $options = {
domain => $self->cookie_domain,
Expand Down Expand Up @@ -126,6 +128,18 @@ C<expiration> and C<expires> session values.
# Delete whole session by setting an expiration date in the past
$c->session(expires => 1);
=head2 deserialize
my $cb = $sessions->deserialize;
$sessions = $sessions->deserialize(sub {...});
A callback used to deserialize sessions, defaults to L<Mojo::JSON/"j">.
$sessions->deserialize(sub {
my $bytes = shift;
return {};
});
=head2 secure
my $bool = $sessions->secure;
Expand All @@ -134,6 +148,19 @@ C<expiration> and C<expires> session values.
Set the secure flag on all session cookies, so that browsers send them only
over HTTPS connections.
=head2 serialize
my $cb = $sessions->serialize;
$sessions = $sessions->serialize(sub {...});
A callback used to serialize sessions, defaults to
L<Mojo::JSON/"encode_json">.
$sessions->serialize(sub {
my $hash = shift;
return '';
});
=head1 METHODS
L<Mojolicious::Sessions> inherits all methods from L<Mojo::Base> and
Expand Down

0 comments on commit 563a2c7

Please sign in to comment.