■実装
app/Controller/UsersController.php
App::uses('AppController', 'Controller'); /** * Users Controller * @property User $User */ class UsersController extends AppController { public $uses = array('User'); public $components = array( 'Session', 'Auth' => array( 'loginRedirect' => array('controller' => 'users', 'action' => 'index'),// ログイン後のリダイレクト先 'logoutRedirect' => array('controller' => 'pages', 'action' => 'display', 'home')// ログアウト後のリダイレクト先 ) ); public function beforeFilter() { //$this->Auth->allow('index'/*, 'add'*/);// 認証を除外するアクションを指定する } /** * ユーザを追加する画面 * @return void */ public function add() { /*if ($this->request->is('post')) { $this->User->create(); if ($this->User->save($this->request->data)) { $this->Session->setFlash(__('The user has been saved')); $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.')); } }*/ } /** * ログイン画面 * @return void */ public function admin_login() { if ($this->Auth->login()) { $this->redirect($this->Auth->redirect()); } else { $this->Session->setFlash(__('Invalid username or password, try again')); } } /** * ログアウト画面 * @return void */ public function admin_logout() { $this->redirect($this->Auth->logout()); } }
app/Model/User.php
App::uses('AppModel', 'Model'); /** * User Model * ユーザのモデル */ class User extends AppModel { public function __construct($id = false, $table = null, $ds = null) { $this->useDbConfig = Configure::read('Config.environment'); parent::__construct($id, $table, $ds); } /** * 保存前に実行される * @return void */ public function beforeSave() { if (isset($this->data[$this->alias]['password'])) { $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']); } return true; } }
Cake1系ではpasswordというカラム名が自動的にハッシュ化されていた。Cake2系では上述のように実装する必要がある。
app/View/Users/admin_login.ctp
以下のようにログインフォームを記述する。
<?php echo $this->Session->flash('auth'); ?> <?php echo $this->Form->create('User');?> <fieldset> <legend><?php echo __('Please enter your username and password'); ?></legend> <?php echo $this->Form->input('username'); echo $this->Form->input('password'); ?> </fieldset> <?php echo $this->Form->end(__('Login'));?>
$thisを介してSessionとFormにアクセスするところがCake2系では異なる。
app/View/Users/admin_logout.ctp
<h3>ログアウトしました。</h3>
■参考
殆ど参考文献の簡略化日本語版だな。