CakePHP2で認証処理を追加する方法
AppContorller.php
public $components = array( 'Auth' => array( 'loginAction' => array( "controller"=>"login", "action"=>"index" ), 'loginRedirect' => array( 'controller' => 'posts', 'action' => 'index' ), 'authenticate' => array( 'Form' => array( 'passwordHasher' => 'Blowfish', 'hashType' => 'sha1', 'userModel' => 'Users', "fields"=>array( "username"=>"account", "password"=>"password" ) ) ) ) );
loginAction: ログインフォームのページを指定
loginRedirect: ログイン処理後に移動するページを師弟
authenticate: 認証処理の種類を指定
User.php(モデル)
App::uses('BlowfishPasswordHasher', 'Controller/Component/Auth');
class User extends AppModel {
// ハッシュ処理
public function beforeSave($options = array()) {
if (isset($this->data[$this->alias]['password'])) {
$passwordHasher = new BlowfishPasswordHasher();
$this->data[$this->alias]['password'] = $passwordHasher->hash(
$this->data[$this->alias]['password']
);
}
return true;
}
}
パスワードをハッシュ化する処理
ログイン処理をします。
LoginController.php
class LoginController extends AppController{
public function initialize() {
parent::initialize();
}
//コントローラー
public function index() {
$this->loadModel("Users");
if($this->request->is('post')){//POST送信なら
if($this->Auth->login($this->data["Users"])){//ログイン成功なら
return $this->redirect($this->Auth->redirectUrl()); //Auth指定のログインページへ移動
}else{ //ログイン失敗なら
$this->Flash->error(__('ユーザ名かパスワードが違います'));
}
}
}
}
AppControllerでAuthの処理を指定しているので、認証をしたくないページにはコントローラーに下記の処理を追加します。
actionを指定すると認証の処理を省けます。
/**
* Controller内共通設定
*/
public function beforeFilter(){
$this->Auth->allow('index', "view", "edit", "add");
}
