File Coverage

blib/lib/Dancer/Plugin/RequireSSL.pm
Criterion Covered Total %
statement 15 32 46.8
branch 0 6 0.0
condition 0 10 0.0
subroutine 5 10 50.0
pod n/a
total 20 58 34.4


line stmt bran cond sub pod time code
1             #
2             # This file is part of Dancer-Plugin-RequireSSL
3             #
4             # This software is copyright (c) 2012 by Natal Ngétal.
5             #
6             # This is free software; you can redistribute it and/or modify it under
7             # the same terms as the Perl 5 programming language system itself.
8             #
9             package Dancer::Plugin::RequireSSL;
10             {
11             $Dancer::Plugin::RequireSSL::VERSION = '0.121370';
12             }
13              
14 1     1   64329 use strict;
  1         2  
  1         40  
15 1     1   6 use warnings;
  1         2  
  1         31  
16              
17 1     1   27 use 5.010;
  1         8  
  1         41  
18              
19 1     1   3725 use Dancer ':syntax';
  1         459710  
  1         6  
20 1     1   1763 use Dancer::Plugin;
  1         1775  
  1         589  
21              
22             #ABSTRACT: Configure your application to redirect all incoming requests to HTTPS
23              
24              
25             register require_ssl => sub {
26             hook before => sub {
27 0     0     my $req = request;
28 0           _redirect_to_ssl($req);
29 0     0     };
30             hook after => sub {
31 0     0     _set_hsts_header();
32 0           };
33             };
34              
35             sub _redirect_to_ssl {
36 0     0     my $req = shift;
37              
38 0 0 0       if ( ! request->secure
39             && setting('environment') ne 'development' ) {
40 0 0 0       if ( $req->base =~ /http:\/\//
41             || $req->header('X-Forwarded-Proto') !~ 'https' ) {
42 0           my $url = 'https://' . $req->host . $req->path;
43              
44 0           return redirect($url);
45             }
46             }
47             }
48              
49             sub _set_hsts_header {
50 0     0     my $settings = plugin_setting;
51 0   0       my $hsts_age = $settings->{hsts_age} // 31536000;
52 0   0       my $subdomains = $settings->{hsts_include_subdomains} // 0;
53 0           my $hsts_policy = "max-age=$hsts_age";
54              
55 0 0         $hsts_policy .= '; includeSubDomains' if $subdomains;
56              
57 0           header 'Strict-Transport-Security' => $hsts_policy;
58              
59 0           return;
60             }
61              
62             register_plugin;
63              
64             1;
65              
66              
67             __END__