+use constant AUTH_TIMEOUT => 5 * 60;
+use constant ACCESSLOG_FORMAT => '%{X-Forwarded-For}i %l %u %t "%r" %>s %b "%{Referer}i" "%{User-agent}i"';
+
+sub CONTENT_SECURITY_POLICY () {
+ my $csp = <<CSP;
+default-src 'none'
+connect-src 'self'
+form-action 'self'
+frame-ancestors 'none'
+img-src 'self' https://static.mindcoding.ro https://www.google-analytics.com/collect
+referrer origin-when-cross-origin
+script-src 'self' https://static.mindcoding.ro/js.js https://www.google-analytics.com/analytics.js
+style-src 'self' https://static.mindcoding.ro/css/
+CSP
+ chomp $csp;
+ $csp =~ s/\n/; /gr;
+}
+
+our $db //= Gruntmaster::Data->connect($ENV{GRUNTMASTER_DSN} // 'dbi:Pg:');
+
+tie my %auth, 'Tie::Hash::Expire', {expire_seconds => AUTH_TIMEOUT};
+
+sub authenticate {
+ my ($user, $pass, $env) = @_;
+ my $key = sha256 "$user:$pass";
+ $env->{'gruntmaster.user'} = $user;
+ return 1 if exists $auth{$key};
+ return unless $db->user($user) && $db->user($user)->check_passphrase($pass);
+ $auth{key} = 1;
+}
+
+sub add_headers {
+ my $app = $_[0];
+ sub {
+ my $resp = $app->($_[0]);
+ my $hdrs = Plack::Util::headers($resp->[1]);
+ $hdrs->set('Content-Security-Policy', CONTENT_SECURITY_POLICY);
+ $hdrs->set('Cache-Control', 'public, max-age=604800') if $_[0]->{PATH_INFO} =~ qr,^/static/,;
+ $resp->[1] = $hdrs->headers;
+ $resp;
+ }