6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Mojolicious::Plugin::Authenticationの使い方

Posted at

Mojolicious::Plugin::Authenticationの使い方を書いてみる。
Mojoliciousでユーザー認証 - Qiitaと組み合わせればもうちょっといいのができるかな?

必須パラメータの説明

パラメータ 意味
autoload_user hookでbefore_dispatchしてるので場合によってはサイトの反応がよくなるかも? とりあえず1にしておけば良い。
validate_user authenticate()が呼ばれた場合に認証処理を行うコールバック関数を記述する。uidを返すこと。
load_user current_user()が呼ばれた場合にユーザーオブジェクトを返すコールバック関数を記述する(引数として上記で返したuidが渡される)
※これ以外にもあるけど、こまけぇこたぁいいんだよ!

スクリプトサンプル

mysample.pl
use Mojolicious::Lite;

{
  package Database;
  my %data = (
    1 => {
      username => "foo",
      password => "bar",
      nickname => "baz",
    },
  );

  sub auth {
    my ($self, $username, $password) = @_;
    foreach my $uid (keys %data) {
      next unless $data{$uid}{username} eq $username;
      last unless $data{$uid}{password} eq $password;
      return $uid;
    }
    return undef;
  }
  sub userdata {
    my ($self, $uid) = @_;
    return $data{$uid};
  }
}

app->secrets(['test']);
plugin 'authentication', {
  autoload_user => 1,
  load_user => sub {
    my $self = shift;
    my $uid  = shift;
    return Database->userdata($uid);
  },
  validate_user => sub {
    my $self      = shift;
    my $username  = shift || '';
    my $password  = shift || '';
    return Database->auth($username, $password);
  },
};

post '/' => sub {
  my $self = shift;
  my $u    = $self->req->param('u');
  my $p    = $self->req->param('p');
  $self->render(text => ($self->authenticate($u, $p)) ? "ok" : "failed");
};

get '/get' => sub {
  my $self = shift;
  $self->render(text => ($self->is_user_authenticated) ? "ok" : "denied");
};

get '/logout' => sub {
  my $self = shift;
  $self->logout();
  $self->render( text => "logout" );
};

get '/info' => sub {
  my $self = shift;
  my $info = $self->current_user;
  $self->render( text => ($info) ? $info->{nickname} : "not login" );
};

use Test::More;
use Test::Mojo;
my $t = Test::Mojo->new;

$t->post_ok('/' => form => { u => "foo", p => "bar" })->status_is(200)->content_is("ok");
$t->get_ok('/get')->status_is(200)->content_is("ok");
$t->get_ok('/info')->status_is(200)->content_is("baz");

$t->get_ok('/logout')->status_is(200)->content_is("logout");
$t->get_ok('/info')->status_is(200)->content_is("not login");

$t->get_ok('/get')->status_is(200)->content_is("denied");

done_testing;

参考

6
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?