Authモジュールによる認証[kohana 3.x]

メモ:  Category:php

kohana 3.xには、認証用のモジュールが付属しています。ここではAuthモジュールとデータベースを 使った認証を行ってみます。

認証環境の準備

modules/authディレクトリにあるmysql.sqlを実行し、データベースへテーブルを作成します。

Authモジュールを使用するためapplication/bootstrap.phpを修正します。

Kohana::modules(array(
    'auth'       => MODPATH.'auth',       // Basic authentication
    // 'cache'      => MODPATH.'cache',      // Caching with multiple backends
    // 'codebench'  => MODPATH.'codebench',  // Benchmarking tool
    'database'   => MODPATH.'database',   // Database access
    // 'image'      => MODPATH.'image',      // Image manipulation
    'orm'        => MODPATH.'orm',        // Object Relationship Mapping
    // 'oauth'      => MODPATH.'oauth',      // OAuth authentication
    //'pagination' => MODPATH.'pagination', // Paging of results
    // 'unittest'   => MODPATH.'unittest',   // Unit testing
    // 'userguide'  => MODPATH.'userguide',  // User guide and API documentation
    ));

ここではデータベースを使った認証を行うため、auth,database,ormの3つのモジュールを有効にします。

次にmodules/auth/configディレクトリにあるauth.phpをapplication/configディレクトリにコピーします。 コピーしたauth.phpの「hash_method」と「salt_pattern」を使って暗号化されるため「salt_pattern」を 変更しておいた方がよいかと思います。

ユーザーの登録

Authモジュールを使う準備ができたので、ユーザーを登録してみます。modules/authディレクトリにあるmysql.sql スクリプトでは、デフォルトで2つのロールを設定しています。

  • login
  • admin

これらのロールとともにユーザーを登録します。まず、accountコントローラーを作成し一時的にユーザーを登録するアクションを追加します。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Account extends Controller_Template_Default {
    function action_adduser()
    {
        $user = ORM::factory('user');
        $user->username = 'admin';
        $user->email    = 'admin@gmail.com';
        $user->password = 'password';
        $user->save();

        // ユーザーにロールを追加します。loginロールは認証に必須となっています。
        $user->add('roles', ORM::factory('role', array('name' => 'admin')));
        $user->add('roles', ORM::factory('role', array('name' => 'login')));
    }
}

※認証には、loginロールが必須となっています。

上記メソッドが実行されることでuserテーブルにadminユーザーが登録され、roles_usersテーブルにadminユーザーに対する ロールが2つ登録されます。

ログインとログアウト

ログインとログアウトを実装します。

<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Account extends Controller_Template_Default {

    public function action_signin()
    {
        $this->template->content = View::factory('account/signin');

        // ログイン済みの場合
        if(Auth::instance()->logged_in()!= 0){
            // リダイレクト
            Request::instance()->redirect('admin/index');
        }

        if ($_POST)
        {
            // Instantiate a new user
            $user = ORM::factory('user');

            // ログイン
            $status = $user->login($_POST);

            if ($status)
            {
                // ログイン成功 リダイレクト
                Request::instance()->redirect('admin/index');
            }else
            {
                // エラーメッセージ
                $content->errors = $_POST->errors('signin');
            }
        }
    }

    public function action_signout()
    {
        // ログアウト
        Auth::instance()->logout();

        // ログイン画面へリダイレクト
        Request::instance()->redirect('account/signin');
    }
}

signinのテンプレートは、usernameとpasswordを渡せるよう次のように作成します。

<?php echo Form::open();?>
<fieldset>
<div>
<?php echo Form::label('username','username');?>
<?php echo Form::input('username');?>
<?php echo Form::label('password','password');?>
<?php echo Form::password('password');?>
</div>
<div>
<?php echo Form::button(NULL, 'Login', array('type' => 'submit'));?>
<?php echo Form::button('Cancel', 'Cancel', array('type' => 'button'));?>
</div>
</fieldset>
<?php echo Form::close();?>

bluenote by BBB