Add authentication cache
[plack-app-gruntmaster.git] / app.psgi
1 #!/usr/bin/perl -w
2 use v5.14;
3
4 use Apache2::Authen::Passphrase qw/pwcheck/;
5 use Apache2::AuthzCaps qw/hascaps/;
6 use Gruntmaster::Data;
7 use Plack::App::Gruntmaster;
8 use Plack::Builder;
9 use Plack::Request;
10 use Digest::SHA qw/sha256/;
11
12 $Apache2::AuthzCaps::rootdir = $Apache2::Authen::Passphrase::rootdir;
13 my $word = qr,(\w+),a;
14
15 sub debug {
16 local $Log::Log4perl::caller_depth = $Log::Log4perl::caller_depth + 1;
17 $_[0]->{'psgix.logger'}->({qw/level debug message/ => $_[1]})
18 }
19
20 sub some_auth_required {
21 my $r = Plack::Request->new($_[0]);
22 return 1 if $_[0]->{'gruntmaster.reqadmin'} || $r->path eq '/action/passwd' || $r->path =~ m,/pb/$word/submit$,;
23 0
24 }
25
26 sub admin_required {
27 local $_ = $_[0];
28 return 1 if m,^/pb/$word, && problem_private $1;
29 return 1 if m,^/log/(?:job|src)/$word, && job_private $1;
30 return 1 if m,^/ct/$word/(?:pb|log), && time < contest_start $1;
31 return 1 if m,^/ct/$word/log/src, && time < contest_end $1;
32 0
33 }
34
35 sub require_admin {
36 my $app = $_[0];
37 sub {
38 *__ANON__ = "require_admin_middleware";
39 my $env = $_[0];
40 my $r = Plack::Request->new($env);
41 $env->{'gruntmaster.reqadmin'} = 1 if admin_required $r->path;
42 $app->($env)
43 }
44 }
45
46 my %authen_cache;
47
48 sub authenticate {
49 my ($user, $pass, $env) = @_;
50 my $cache_key = sha256 "$user:$pass";
51 my $time = $authen_cache{$cache_key} // 0;
52 if ($time >= time - 300) {
53 return 1;
54 } else {
55 delete $authen_cache{$cache_key};
56 }
57
58 return unless eval {
59 pwcheck $user, $pass;
60 1
61 };
62 $authen_cache{$cache_key} = time;
63
64 return if $env->{'gruntmaster.reqadmin'} && !hascaps $user, 'gmadm';
65 1
66 }
67
68 builder {
69 enable 'ContentLength';
70 enable_if { $_[0]->{PATH_INFO} =~ qr,^/static/,} Header => set => ['Cache-Control', 'public, max-age=604800'];
71 enable 'Static', path => qr,^/static/,;
72 enable 'Log4perl', category => 'plack', conf => 'log.conf';
73 enable \&require_admin;
74 enable_if \&some_auth_required, 'Auth::Basic', authenticator => \&authenticate, realm => 'Gruntmaster 6000';
75 Plack::App::Gruntmaster->to_app
76 }
This page took 0.026419 seconds and 5 git commands to generate.