Permalink
Browse files

Allow throwing exception instead of redirecting upon unauthorized acc…

…ess attempt. Closes #591
  • Loading branch information...
1 parent feda6e0 commit 1c0492eb8b73ffa8c10bf80bb9097066dba2f5e8 @ADmad ADmad committed Oct 2, 2012
@@ -212,6 +212,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.
*
* @var array
@@ -322,6 +331,21 @@ public function startup(Controller $controller) {
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)) {
@@ -908,6 +908,30 @@ public function testDefaultToLoginRedirect() {
}
/**
+ * 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
*
* @return void

0 comments on commit 1c0492e

Please sign in to comment.