5丁目通信(仮称)

とある5丁目で活動する還暦間近のWebプログラマーの覚え書きです。それとかかってくる迷惑電話や、家業のアパート経営について。

CakePHP2で管理者用ページだけの認証を行う話し


ユーザー認証と管理者認証を別のモデルで分けたいときの

管理者用の認証をAppController.で定義してしまう。isAdmin()はadmin_***のアクションを呼んだかどうかの判定。

app/Controller/AppController.php

class AppController extends Controller {
  public $components = array('Auth');

  public function beforeFilter() {
    if ($this->isAdmin()) {
      $this->Auth->authenticate = array(
      'Form' => array(
        'userModel' => 'User', //ユーザー情報のモデル
        ),
      );

      $this->Auth->loginAction = '/admin/users/login'; //ログインを行なうaction
      $this->Auth->loginRedirect = '/admin/'; //ログイン後のページ
      $this->Auth->logoutRedirect = '/admin/'; //ログアウト後のページ
      $this->Auth->authError = 'ログインしてください。';

    } else {
      $this->Auth->allow('*');
    }
  }
}

大分はっしょっているけど。こんな感じ。

あとは、ユーザー認証したいコントローラーでAuthコンポーネントを定義しておく。

ブログランキング・にほんブログ村へ 人気ブログランキング

%d人のブロガーが「いいね」をつけました。