From 1c0492eb8b73ffa8c10bf80bb9097066dba2f5e8 Mon Sep 17 00:00:00 2001 From: ADmad Date: Tue, 2 Oct 2012 20:27:41 +0530 Subject: [PATCH] Allow throwing exception instead of redirecting upon unauthorized access attempt. Closes #591 --- .../Controller/Component/AuthComponent.php | 24 +++++++++++++++++++ .../Component/AuthComponentTest.php | 24 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/lib/Cake/Controller/Component/AuthComponent.php b/lib/Cake/Controller/Component/AuthComponent.php index 60d298a62..5b667bf36 100644 --- a/lib/Cake/Controller/Component/AuthComponent.php +++ b/lib/Cake/Controller/Component/AuthComponent.php @@ -211,6 +211,15 @@ class AuthComponent extends Component { */ public $authError = null; +/** + * Controls handling of unauthorized access. By default unauthorized user is + * redirected to the referrer url or AuthComponent::$loginAction or '/'. + * If set to false a ForbiddenException exception is thrown instead of redirecting. + * + * @var boolean + */ + public $unauthorizedRedirect = true; + /** * Controller actions for which user validation is not required. * @@ -322,6 +331,21 @@ class AuthComponent extends Component { return true; } + return $this->_unauthorized($controller); + } + +/** + * Handle unauthorized access attempt + * + * @param Controller $controller A reference to the controller object + * @return boolean Returns false + * @throws ForbiddenException + */ + protected function _unauthorized(Controller $controller) { + if (!$this->unauthorizedRedirect) { + throw new ForbiddenException($this->authError); + } + $this->flash($this->authError); $default = '/'; if (!empty($this->loginRedirect)) { diff --git a/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php b/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php index 59c1aa6c6..d55c62c35 100644 --- a/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php +++ b/lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php @@ -907,6 +907,30 @@ class AuthComponentTest extends CakeTestCase { $this->Auth->startup($Controller); } +/** + * Throw ForbiddenException if AuthComponent::$unauthorizedRedirect set to false + * @expectedException ForbiddenException + * @return void + */ + public function testForbiddenException() { + $url = '/party/on'; + $this->Auth->request = $CakeRequest = new CakeRequest($url); + $this->Auth->request->addParams(Router::parse($url)); + $this->Auth->authorize = array('Controller'); + $this->Auth->authorize = array('Controller'); + $this->Auth->unauthorizedRedirect = false; + $this->Auth->login(array('username' => 'baker', 'password' => 'cake')); + + $CakeResponse = new CakeResponse(); + $Controller = $this->getMock( + 'Controller', + array('on', 'redirect'), + array($CakeRequest, $CakeResponse) + ); + + $this->Auth->startup($Controller); + } + /** * Test that no redirects or authorization tests occur on the loginAction *