CakePHPのAuthコンポーネントのセットアップメモ。
こんな感じでAdminルーティングが設定してある。
Configure::write('Routing.admin', 'admin');
Router::connect('/admin', array('controller' => 'pages', 'action' => 'index', 'admin' => true));
function beforeFilter()
{
if (preg_match('/^admin/', $this->params['url']['url'])) {
$this->view = 'Theme';
$this->theme = 'admin';
}
}
ほとんどのコントローラーにAdmin用のメソッドが存在してるので AppControlerでAuthコンポーネント使うぞ宣言する。
var $components = array('Auth');
ヘルパーはbeforeFilter()で追加できるけどAuthはできない。(というかコンポーネントはできないのかな?)
function beforeFilter()
{
$this->helpers[] = 'HogeHelper';//出来る
$this->components[] = 'Auth';//出来ない
}
利用するテーブルとカラムを変えるにはAuth::userModelとAuth::fieldsを設定する。
$this->Auth->userModel = 'Member';
$this->Auth->fields = array(
'username' => 'account',
'password' => 'secretkey'
);
エラーメッセージなどの設定と、admin/以外のアクションは認証なしで 利用できるように設定する。
function beforeFilter()
{
if (preg_match('/^admin/', $this->params['url']['url'])) {
$this->view = 'Theme';
$this->theme = 'admin';
$this->Auth->userModel = 'Member';
$this->Auth->fields = array(
'username' => 'account',
'password' => 'secretkey'
);
$this->Auth->loginError = 'パスワードが違います。';
$this->Auth->authError = '管理者用のページです。';
} else {
// admin/以外は認証不要
$this->Auth->allow('*');
}
}
マニュアルそのまんまって感じです。
function admin_login() {}
function admin_logout() {
$this->redirect($this->Auth->logout());
}
こちらもマニュアルのサンプルがそのまま使える。 Users以外のモデルやカラムの場合変更が必要となる。
if ($session->check('Message.auth')) $session->flash('auth');
echo $form->create('Member', array('action' => 'login'));
echo $form->input('account');
echo $form->input('secretkey');
echo $form->end('Login');
想像以上に簡単だ。単純にAuthを使う場合、悩むことはなさそう。 問題はACLとかAROとかACOが絡んできた時かな。そもそも機能がいまいち理解できてないしw
Authコンポーネントを有効にしたら
Warning: Cannot modify header information
というエラーが出た。ググってみるとheaderの前に何かしらの文字が出力されている可能性があるとのこと。 もしくはutf-8のbom付きだとなる模様。
まず疑うべきはコントローラーとかモデルの最後の「?>」の後ろに改行などがないか。
PHPの「?>」はZend Flameworkのコーディング規約でも書くなと言われていたはずなので、 書かないのがPHP界の常識なはず。でも書くな書くなと言われてもホントに?ほんとにいいの書かなくて? ってどーにも不安だったんですがこれからはきっちりと削除しようかとおもいました。
/ 金額 : ¥ 2,940
1-5
6-10
/ 金額 : ¥ 3,465
/ 金額 : ¥ 3,150
/ 金額 : ¥ 2,699
/ 金額 : ¥ 3,497
/ 金額 : ¥ 3,675