ele_eel's diary

プログラムの事を少しと、デジタル系買物記。

Kohanaのログイン認証とAuthlite.php

Kohanaにはデフォルトでログイン認証モジュール Auth が用意されてますが、対応する config ファイルは一つしか設定できません。なので、ログインを複数設定できないようで、使い勝手がイマイチです。
そこで、Authlite というライブラリを公開されている方がいたので使ってみることに。

Authlite, for User Authentication

http://www.beyondcoding.com/tag/authlite/

要はコンフィグファイルで、使い分けのできる Auth ということです。

使い方をそのまま引用

// Authlite instance
$this->authlite = Authlite::instance('authlite');
 
// login check
if ( ! $this->authlite->logged_in() && Router::$method != 'login')
{
	url::redirect(Router::$controller.'/login');
}
else
{
	// assigns the user object
	$this->user = $this->authlite->get_user();
}

インスタンスを作る際にコンフィグファイルを指定するだけ。あとは Auth と同じ感じ。
コンフィグの設定は、

/**
* User model
*/
$config['user_model'] = 'user';
 
/**
* Username column
*/
$config['username'] = 'username';
 
/**
* Password column
*/
$config['password'] = 'password';
 
/**
* Session column
*/
$config['session'] = 'session';
 
/**
* Type of hash to use for passwords. Any algorithm supported by the hash function
* can be used here.
* @see http://php.net/hash
* @see http://php.net/hash_algos
*/
$config['hash_method'] = 'sha1';
 
/**
* Set the auto-login (remember me) cookie lifetime, in seconds. The default
* lifetime is two weeks.
*/
$config['lifetime'] = 1209600;
 
/**
* Set the session key that will be used to store the current user.
*/
$config['session_key'] = 'authlite_user';

Auth と違う点は、Auth 用のテーブルを別途用意しなくていいことですかね。
既存のデータベースにも組み込みやすいんじゃないでしょうか。注意すべきは User model は ORM を継承する必要があること。

実際使ってみて、あとAuthlite のソースを見ていて不都合なことが一点。
オートログインの際に生成されるクッキー名がコンフィグファイルへのパス名を利用しているので、例えばconfig ディレクトリを階層化していたりするとクッキー名にスラッシュが入ってしまうので、セッションエラーになる。なので、コンフィグに項目を追加してみました。例えばこんな感じ。

/**
* オートログインクッキー名
*/
$config['auto_login_cookie'] = 'auto_login';

Authlite.phpを以下のように修正

//	cookie::set("authlite_{$this->config_name}_autologin", $token, $this->config['lifetime']);
	cookie::set($this->config['auto_login_cookie'], $token, $this->config['lifetime']);

オートログイン用クッキーを指定している箇所全て修正します。メソッド logged_in(), login(), logout() で修正する必要があります。
これで認証は簡単に行うことができました。