]> iEval git - gruntmaster-page.git/blob - app.psgi
85e8847a44e8b7420e8cefca46ec862075f06cfe
[gruntmaster-page.git] / app.psgi
1 #!/usr/bin/perl -w
2 use v5.14;
3 no if $] >= 5.017011, warnings => 'experimental::smartmatch';
4
5 use Gruntmaster::Data;
6 use Plack::App::Gruntmaster;
7 use Plack::Builder;
8 use Plack::Request;
9 use Plack::Util;
10 use Digest::SHA qw/sha256/;
11 use Log::Log4perl;
12 use Tie::Hash::Expire;
13
14 use constant AUTH_TIMEOUT => 5 * 60;
15 use constant ACCESSLOG_FORMAT => 'combined';
16
17 sub CONTENT_SECURITY_POLICY () {
18 my $csp = <<CSP;
19 default-src 'none'
20 connect-src 'self'
21 form-action 'self'
22 frame-ancestors 'none'
23 img-src 'self'
24 referrer origin-when-cross-origin
25 script-src 'self'
26 style-src 'self'
27 CSP
28 chomp $csp;
29 $csp =~ s/\n/; /gr;
30 }
31
32 my $db;
33
34 tie my %auth, 'Tie::Hash::Expire', {expire_seconds => AUTH_TIMEOUT};
35
36 sub authenticate {
37 my ($user, $pass, $env) = @_;
38 my $key = sha256 "$user:$pass";
39 $env->{'gruntmaster.user'} = $user;
40 return 1 if exists $auth{$key};
41 return unless $db->user($user) && $db->user($user)->check_passphrase($pass);
42 $auth{key} = 1;
43 }
44
45 sub add_database {
46 my $app = $_[0];
47 sub {
48 my ($env) = @_;
49 $db //= Gruntmaster::Data->connect($ENV{GRUNTMASTER_DSN} // 'dbi:Pg:');
50 $env->{'gruntmaster.dbic'} = $db;
51 $app->($env)
52 }
53 }
54
55 sub add_headers {
56 my $app = $_[0];
57 sub {
58 my $resp = $app->($_[0]);
59 my $hdrs = Plack::Util::headers($resp->[1]);
60 $hdrs->set('Content-Security-Policy', CONTENT_SECURITY_POLICY);
61 $hdrs->set('Cache-Control', 'public, max-age=604800') if $_[0]->{PATH_INFO} =~ qr,^/static/,;
62 $resp->[1] = $hdrs->headers;
63 $resp;
64 }
65 }
66
67 Log::Log4perl->init_once('log.conf');
68 my $access_logger = Log::Log4perl->get_logger('access');
69 $ENV{DBIC_NULLABLE_KEY_NOWARN} = 1;
70
71 builder {
72 enable_if { $_[0]->{PATH_INFO} eq '/ok' } sub { sub{ [200, [], []] }};
73 enable 'AccessLog', format => ACCESSLOG_FORMAT, logger => sub { $access_logger->info(@_) };
74 enable 'ContentLength';
75 enable \&add_headers;
76 enable 'Static', path => qr,^/static/,;
77 enable 'Log4perl', category => 'plack';
78 enable \&add_database;
79 enable_if { shift->{HTTP_AUTHORIZATION} } 'Auth::Basic', authenticator => \&authenticate, realm => 'Gruntmaster 6000';
80 Plack::App::Gruntmaster->run_if_script
81 }
This page took 0.054173 seconds and 3 git commands to generate.