Browse Source

Allow throwing exception instead of redirecting upon unauthorized access attempt. Closes #591

ADmad 13 years ago
parent
commit
1c0492eb8b

+ 24 - 0
lib/Cake/Controller/Component/AuthComponent.php

@@ -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 @@ 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)) {

+ 24 - 0
lib/Cake/Test/Case/Controller/Component/AuthComponentTest.php

@@ -908,6 +908,30 @@ class AuthComponentTest extends CakeTestCase {
 	}
 
 /**
+ * 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