Amon2

 view release on metacpan or  search on metacpan

share/flavor/Basic/lib/__PATH__/Web/Plugin/Session.pm  view on Meta::CPAN

use strict;
use warnings;
use utf8;

use Amon2::Util;

sub init {
    my ($class, $c) = @_;

    Amon2::Util::add_method($c, 'xsrf_token', \&_xsrf_token);
    Amon2::Util::add_method($c, 'validate_xsrf_token', \&_validate_xsrf_token);

    # Ensure and validate XSRF token.
    $c->add_trigger(
        BEFORE_DISPATCH => sub {
            my ( $c ) = @_;
            _xsrf_token($c); # initialize on first request

            if ($c->req->method ne 'GET' && $c->req->method ne 'HEAD') {
                my $token = $c->req->header('X-XSRF-TOKEN')
                         || $c->req->param('XSRF-TOKEN');
                unless (_validate_xsrf_token($c, $token)) {
                    return $c->create_simple_status_page(
                        403, 'XSRF detected.'
                    );
                }
            }
            return;
        },
    );

    # Expose XSRF token as a readable cookie for JavaScript helper.

share/flavor/Basic/lib/__PATH__/Web/Plugin/Session.pm  view on Meta::CPAN

    my $token = $self->session->get('xsrf_token');

    if (!defined $token || $token eq '') {
        $token = Amon2::Util::random_string(32);
        $self->session->set('xsrf_token' => $token);
    }

    return $token;
}

sub _validate_xsrf_token {
    my ($self, $token) = @_;
    return unless defined $token;

    my $session_token = _xsrf_token($self);
    return defined $session_token && $token eq $session_token;
}

1;
__END__

t/300_setup/02_basic.t  view on Meta::CPAN


test_flavor(sub {
    ok(-f 'Build.PL', 'Build.PL');
	like(slurp('cpanfile'), qr{Plack::Middleware::Session});
	for my $env (qw(development production test)) {
		ok(-f "./config/${env}.pl");
		my $conf = do "./config/${env}.pl";
		is(ref($conf), 'HASH');
	}
    ok(-f './lib/My/App.pm', 'lib/My/App.pm exists');
    like(slurp('./lib/My/App/Web/Plugin/Session.pm'), qr{sub _validate_xsrf_token});
    like(slurp('./script/my-app-server'), qr{Plack::Session::Store::File}, 'uses file session store');
    ok((do './lib/My/App.pm'), 'lib/My/App.pm is valid') or do {
        diag $@;
        diag do {
            open my $fh, '<', './lib/My/App.pm' or die;
            local $/; <$fh>;
        };
    };
    ok(-f './static/js/xsrf-token.js', 'xsrf-token.js exists');
	like(slurp('./cpanfile'), qr{'Teng'\s*,\s*'[0-9.]+'});



( run in 1.744 second using v1.01-cache-2.11-cpan-39bf76dae61 )