From: hylom Date: Fri, 2 Dec 2016 14:59:19 +0000 (+0900) Subject: Plugin: add BasicAuth X-Git-Tag: v0.1.1~1097 X-Git-Url: http://git.osdn.net/view?a=commitdiff_plain;h=3693962be44f16dbc6e5ac78fc451d276065e20a;p=newslash%2Fnewslash.git Plugin: add BasicAuth --- diff --git a/src/newslash_web/lib/Newslash/Plugin/BasicAuth.pm b/src/newslash_web/lib/Newslash/Plugin/BasicAuth.pm new file mode 100644 index 00000000..d62a198a --- /dev/null +++ b/src/newslash_web/lib/Newslash/Plugin/BasicAuth.pm @@ -0,0 +1,30 @@ +package Newslash::Plugin::BasicAuth; +use Mojo::Base 'Mojolicious::Plugin'; + +sub register { + my ($self, $app, $conf) = @_; + + if ($app->config->{BasicAuth}) { + my $password = $app->config->{BasicAuth}->{password}; + my $user = $app->config->{BasicAuth}->{username}; + my $message = $app->config->{BasicAuth}->{message} || "access restricted"; + return if (!$password || !$user); + + $app->hook(before_dispatch => sub { + my $c = shift; + my $auth = $c->req->url->to_abs->userinfo; + if ($auth) { + my ($u, $p) = split(/:/, $auth, 2); + if ($u eq $user && $p eq $password) { + return; + } + } + $c->res->headers->www_authenticate("Basic realm=\"$message\""); + $c->res->code(401); + $c->res->body('Authorization required'); + return $c->rendered; + }); + } +} + +1; diff --git a/src/newslash_web/lib/Newslash/Web.pm b/src/newslash_web/lib/Newslash/Web.pm index d5b90b98..9eb9b650 100644 --- a/src/newslash_web/lib/Newslash/Web.pm +++ b/src/newslash_web/lib/Newslash/Web.pm @@ -20,6 +20,11 @@ sub startup { # stash for plugins $app->config->{_Plugins} = {}; + # use BasicAuth? + if ($app->config->{BasicAuth} && $app->config->{BasicAuth}->{enable}) { + $app->plugin('Newslash::Plugin::BasicAuth'); + } + # use TimeLimitedCache my $cache_opts = $app->config->{Cache} || {}; $app->plugin('Newslash::Plugin::TimeLimitedCache');