0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

CakePHP2、Authで認証項目を追加したい時

0
Posted at

ログイン認証で、普通はIDとパスワードだけだが、ここになんか例えば学校コードみたいのも入れたい、なんて話になった時にどうするか?
学校に所属する生徒=ユーザーという設定で考えてみる。
とりあえず学校(Schoolモデル)にコードという項目を追加して、Userモデルでアソシエーションを貼っておく。

User.php
	public $belongsTo = array(
		'School' => array(
			'className' => 'School',
			'foreignKey' => 'school_id',
			'conditions' => '',
			'fields' => '',
			'order' => ''
		),
    )

これでどうだろ。
SchoolとUserを紐付けているのはUserテーブル上のschool_idだが、ログインする時はA001みたいな学校コード(これはSchoolテーブル側)を使いたい、ということだと思ってくれ。

で、ビューにフォームを追加。

login_ctp
	<?php
		echo $this->Form->input('School.code', array('label' => array('text' => '学校コード')));
		echo $this->Form->input('username', array('label' => array('text' => 'ユーザーID')));
		echo $this->Form->input('password', array('label' => array('text' => 'パスワード')));
	?>

こんな感じか。

で。コントローラにbeforeFilterで、

UsersConttoller.php
	public function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->allow('logout');
        if ($this->request->is('post') && isset($this->request->data['School']['code'])) {
            $code = $this->request->data['School']['code'];
            $this->Auth->authenticate = array(
                'Form' => array('passwordHasher' => 'Blowfish', 'scope' => array('School.code' => $code))
            );
        }
	}

scopeで学校コードを追加する。
Authの設定として、AppController.phpの方で、以下のような指定をしていると思うが、

AppController.php
	public $components = array(
		'Paginator', 'Flash', 'Session', 'Security',
		'Auth' => array(
			'logoutRedirect' => array(
				'controller' => 'users',
				'action' => 'login'
			),
			'authenticate' => array(
				'Form' => array(
                    'passwordHasher' => 'Blowfish'
				)
			)
		)
	);

それを部分的に上書きしているような感じである。
コントローラ側ではbeforeFilterの中に書くのが味噌だ。

0
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?