Welcome to the Cookbook

loading...

5.2.6.9 autoRedirect

The original text for this section has changed since it was translated. Please help resolve this difference. You can:

More information about translations

通常、 AuthComponent は認証を実行してすぐ、自動的にリダイレクトを実行します。しかしユーザをリダイレクトする前に、さらに何かをチェックしたいかもしれません。

<?php
	function beforeFilter() {
		...
		$this->Auth->autoRedirect = false;
	}

	...

	function login() {
	//-- この関数に含まれるコードは、 autoRedirect が false にセットされている時、つまり beforeFilter でだけ動作します。
		if ($this->Auth->user()) {
			if (!empty($this->data)) {
				$cookie = array();
				$cookie['username'] = $this->data['User']['username'];
				$cookie['password'] = $this->data['User']['password'];
				$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
				unset($this->data['User']['remember_me']);
			}
			$this->redirect($this->Auth->redirect());
		}
		if (empty($this->data)) {
			$cookie = $this->Cookie->read('Auth.User');
			if (!is_null($cookie)) {
				if ($this->Auth->login($cookie)) {
					//  この分岐では認証のメッセージをクリアしてください。
					$this->Session->del('Message.auth');
					$this->redirect($this->Auth->redirect());
				}
			}
		}
    }
?>
  1. <?php
  2. function beforeFilter() {
  3. ...
  4. $this->Auth->autoRedirect = false;
  5. }
  6. ...
  7. function login() {
  8. //-- この関数に含まれるコードは、 autoRedirect が false にセットされている時、つまり beforeFilter でだけ動作します。
  9. if ($this->Auth->user()) {
  10. if (!empty($this->data)) {
  11. $cookie = array();
  12. $cookie['username'] = $this->data['User']['username'];
  13. $cookie['password'] = $this->data['User']['password'];
  14. $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
  15. unset($this->data['User']['remember_me']);
  16. }
  17. $this->redirect($this->Auth->redirect());
  18. }
  19. if (empty($this->data)) {
  20. $cookie = $this->Cookie->read('Auth.User');
  21. if (!is_null($cookie)) {
  22. if ($this->Auth->login($cookie)) {
  23. // この分岐では認証のメッセージをクリアしてください。
  24. $this->Session->del('Message.auth');
  25. $this->redirect($this->Auth->redirect());
  26. }
  27. }
  28. }
  29. }
  30. ?>

このコードの login 関数は、beforeFilter で $autoRedirect を false にセットしない限り実行されません。この login 関数のコードは、認証が試みられただけに実行されます。ここはログインが成功したかどうか確定する最もよい場所です。(例えば、最終ログイン日時をログに記録するなど)