File Coverage

blib/lib/Mojolicious/Plugin/SecureOnly.pm
Criterion Covered Total %
statement 25 25 100.0
branch 15 20 75.0
condition 5 6 83.3
subroutine 4 4 100.0
pod 1 2 50.0
total 50 57 87.7


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