File Coverage

blib/lib/Mojolicious/Plugin/WithCSRFProtection.pm
Criterion Covered Total %
statement 22 23 95.6
branch 6 8 75.0
condition 6 6 100.0
subroutine 5 5 100.0
pod 1 1 100.0
total 40 43 93.0


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::WithCSRFProtection;
2              
3             # ABSTRACT: Mojolicious plugin providing CSRF protection at the routing level
4              
5 2     2   2189327 use Mojo::Base 'Mojolicious::Plugin';
  2         8  
  2         23  
6              
7             our $VERSION = '1.02';
8              
9             sub register {
10 2     2 1 111 my ( $self, $app ) = @_;
11              
12 2         17 my $routes = $app->routes;
13              
14             $app->helper(
15             'reply.bad_csrf' => sub {
16 9     9   439 my ($c) = @_;
17 9         42 $c->res->code(403);
18 9 100       205 $c->render_maybe('bad_csrf')
19             or $c->render( text => 'Failed CSRF check' );
20 9         20822 return;
21             }
22 2         33 );
23              
24             $routes->add_condition(
25             with_csrf_protection => sub {
26 15     15   222709 my ( $route, $c ) = @_;
27              
28 15   100     74 my $csrf = $c->req->headers->header('X-CSRF-Token')
29             || $c->param('csrf_token');
30              
31 15 100 100     4814 unless ( $csrf && $csrf eq $c->csrf_token ) {
32 9 50       2721 $c->reply->bad_csrf unless $c->stash->{'mojo.finished'};
33 9         61 return;
34             }
35              
36 6         2501 return 1;
37             }
38 2         2053 );
39              
40             $routes->add_shortcut(
41             with_csrf_protection => sub {
42 1     1   1352 my ($route) = @_;
43 1 50       12 if ($Mojolicious::VERSION >= 9) {
44 1         5 return $route->requires( with_csrf_protection => 1 );
45             } else {
46 0         0 return $route->over( with_csrf_protection => 1 );
47             }
48             }
49 2         74 );
50              
51 2         177 return;
52             }
53              
54             1;
55              
56             __END__