auth機能を使って、管理画面を作る。
モデル
[User]
App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component'); // コンポーネントを追加
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
コントローラー
[AppController]
public $components = array(
'Session',
'Auth' => array(
'authenticate' => array(
'Form' => array(
'userModel' => 'Member', //ユーザー情報のモデル
'fields' => array('username' => 'email') //認証をusernameからemailカラムに変更
)
),
'loginAction' => array('controller' => 'pages','action' => 'login'), //ログインを行なうaction
'loginRedirect' => array('controller' => 'pages', 'action' => 'index'), //ログイン後のページ
'logoutRedirect' => array('controller' => 'pages', 'action' => 'index') //ログアウト後のページ
)
);
[UserController]
public function beforeFilter()
{
$this->layout = 'admin';
$this->Auth->allow('add', 'login');
}
public function login() {
if($this->request->is('post')) {
if($this->Auth->login()) {
return $this->redirect($this->Auth->redirect());
} else {
$this->Session->setFlash(__('Username or password is incorrect'), 'default', array(), 'auth');
}
}
}
public function logout($id = null)
{
$this->redirect($this->Auth->logout());
}
ビュー
[login.ctp]
test