File Coverage

blib/lib/Mojolicious/Plugin/SecureOnly.pm
Criterion Covered Total %
statement 17 17 100.0
branch 5 8 62.5
condition 5 6 83.3
subroutine 4 4 100.0
pod 1 2 50.0
total 32 37 86.4


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::SecureOnly;
2 1     1   479 use Mojo::Base 'Mojolicious::Plugin';
  1         1  
  1         5  
3              
4             our $VERSION = '0.02';
5              
6             has 'conf' => sub { {} };
7              
8             sub register {
9 1     1 1 32 my ($self, $app, $conf) = @_;
10              
11 1 50       1 $self->conf({%$conf, %{$app->config('SecureOnly')||{}}});
  1         8  
12              
13             $app->hook(before_dispatch => sub {
14 4     4   31040 my $c = shift;
15              
16 4 50       11 return if $c->req->is_secure;
17 4 100 100     96 return $app->log->warn('SecureOnly disabled; Reverse Proxy support not enabled in Mojolicious, see http://mojolicious.org/perldoc/Mojo/Server#reverse_proxy')
18             if !$c->tx->req->reverse_proxy && detect_proxy($c);
19              
20 3         43 my $url = $c->req->url->to_abs;
21 3         329 $url->scheme('https');
22 3 50       14 $url->port($self->conf->{secureport}) if $self->conf->{secureport};
23 3         18 $c->app->log->debug("SecureOnly enabled; Request for insecure resource, redirecting to $url");
24 3         469 $c->redirect_to($url);
25 1         27 });
26             }
27              
28             sub detect_proxy {
29 2     2 0 13 my $c = shift;
30 2   66     3 return $c->tx->req->headers->header('X-Forwarded-For') || $c->tx->req->headers->header('X-Forwarded-Proto')
31             }
32              
33             1;
34              
35             __END__