OSDN Git Service

Plugin: add BasicAuth
authorhylom <hylom@users.sourceforge.jp>
Fri, 2 Dec 2016 14:59:19 +0000 (23:59 +0900)
committerhylom <hylom@users.sourceforge.jp>
Fri, 2 Dec 2016 14:59:19 +0000 (23:59 +0900)
src/newslash_web/lib/Newslash/Plugin/BasicAuth.pm [new file with mode: 0644]
src/newslash_web/lib/Newslash/Web.pm

diff --git a/src/newslash_web/lib/Newslash/Plugin/BasicAuth.pm b/src/newslash_web/lib/Newslash/Plugin/BasicAuth.pm
new file mode 100644 (file)
index 0000000..d62a198
--- /dev/null
@@ -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;
index d5b90b9..9eb9b65 100644 (file)
@@ -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');