2008-03-05 22:25:06

Catalyst::Plugin::Authentication 新版

[Catalyst]

知らなかった
ex) http://catalyst.g.hatena.ne.jp/lapis25/20070806
ex) http://search.cpan.org/~jayk/Catalyst-Plugin-Authentication/
試してみる
$ vim lib/MyApp.pm

use Catalyst qw/
       (略)
       Authentication
       Authentication::Store::DBIC
       Authentication::Credential::Password
       /;

use Catalyst qw/
        (略)
        Authentication
        /;

$ vim myapp.yml

authentication:
  dbic:
    user_class: MyAppDB::User
    user_field: email
    password_field: password

authentication:
  default_realm: members
  realms:
    members:
      credential:
        class: Password
        password_field: password
        password_type: clear
      store:
        class: DBIx::Class
        user_class: MyAppDB::User
        id_field: email

$ vim lib/MyApp/Controller/Auth.pm

if ($c->login($c->stash->{email}, $password)) {
    $c->res->redirect( $c->req->{uri} );
}

if ($c->authenticate({email => $c->stash->{email}, password => $password})) {
    $c->res->redirect( $c->req->{uri} );
}

嬉しいこと。
こういうテーブルの時

+------------------+--------------+------+-----+-------------------+----------------+
| Field            | Type         | Null | Key | Default           | Extra          |
+------------------+--------------+------+-----+-------------------+----------------+
| id               | int(11)      | NO   | PRI | NULL              | auto_increment |
| email            | varchar(255) | NO   |     |                   |                |
| password         | varchar(255) | NO   |     |                   |                |
+------------------+--------------+------+-----+-------------------+----------------+
email と password で認証すると、以前は Catalyst::Plugin::Authentication::User の為 $c->user->id に email の値が入ってしまっていて不便だった。

今はテーブルの id が入るようになった!

同一アプリケーションで認証を複数別々に使う場合
$ vim myapp.yml

authentication:
  default_realm: bluegroup
  realms:
    bluegroup:
      credential:
        class: Password
        password_field: password
        password_type: clear
      store:
        class: DBIx::Class
        user_class: MyAppDB::Blue
        id_field: email
    redgroup:
      credential:    #bluegroupとは異なるcredentialと内容が使える
        class: Password
        password_field: password
        password_type: clear
      store:    #bluegroupとは異なるstoreと内容が使える
        class: DBIx::Class
        user_class: MyAppDB::Red
        id_field: nickname

$ vim lib/MyApp/Controller/Auth.pm
#デフォルト(bluegroup)の場合は
if ($c->authenticate({email => $c->stash->{email}, password => $password})) {
    $c->res->redirect( $c->req->{uri} );
}
#デフォルトじゃない(redgroup)場合は
if ($c->authenticate({nickname => $c->stash->{nickname}, password => $password},'redgroup')) {
    $c->res->redirect( $c->req->{uri} );
}

if (!$c->user_exists or ( $c->user->get('hoge') ne $c->stash->{hoge}) ) {
    $c->detach('login');
}
のように $c->user_exists プラスアルファで認証確認