+sub admin_required {
+ local $_ = $_[0];
+ return problem_owner $1 if m,^/pb/$word, && problem_private $1;
+ return job_user $1 if m,^/log/(?:job|src)/$word, && job_private $1;
+ return contest_owner $1 if m,^/ct/$word/(?:pb|log), && time < contest_start $1;
+ if (m,^/ct/$word/log/(?:job|src)/$word, && time < contest_end $1){
+ local $Gruntmaster::Data::contest = $1;
+ return job_user $2;
+ }
+ 0
+}
+
+sub require_admin {
+ my $app = $_[0];
+ sub {
+ local *__ANON__ = "require_admin_middleware";
+ my $env = $_[0];
+ my $r = Plack::Request->new($env);
+ $env->{'gruntmaster.reqadmin'} = admin_required $r->path;
+ $app->($env)
+ }
+}
+
+my %authen_cache;
+
+sub authenticate {
+ my ($user, $pass, $env) = @_;
+ my $cache_key = sha256 "$user:$pass";
+ my $time = $authen_cache{$cache_key} // 0;
+ if ($time >= time - 300) {
+ return 1;
+ } else {
+ delete $authen_cache{$cache_key};
+ }
+
+ return unless eval {
+ pwcheck $user, $pass;
+ 1
+ };
+ $authen_cache{$cache_key} = time;
+
+ return if $env->{'gruntmaster.reqadmin'} && $env->{'gruntmaster.reqadmin'} ne $user && !hascaps $user, 'gmadm';
+ 1
+}
+
+Log::Log4perl->init('log.conf');
+my $access_logger = Log::Log4perl->get_logger('access');
+