Commit 9d663bed by Qiang Xue

Merge pull request #198 from creocoder/auth-manager

[WIP] Auth manager
parents 1ccce67f b9ea7e6f
<?php
namespace yiiunit\framework\rbac;
use yii\rbac\Assignment;
use yii\rbac\Item;
use yiiunit\TestCase;
abstract class ManagerTestBase extends TestCase
{
/** @var \yii\rbac\PhpManager|\yii\rbac\DbManager */
protected $auth;
public function testCreateItem()
{
$type = Item::TYPE_TASK;
$name = 'editUser';
$description = 'edit a user';
$bizRule = 'checkUserIdentity()';
$data = array(1, 2, 3);
$item = $this->auth->createItem($name, $type, $description, $bizRule, $data);
$this->assertTrue($item instanceof Item);
$this->assertEquals($item->type, $type);
$this->assertEquals($item->name, $name);
$this->assertEquals($item->description, $description);
$this->assertEquals($item->bizRule, $bizRule);
$this->assertEquals($item->data, $data);
// test shortcut
$name2 = 'createUser';
$item2 = $this->auth->createRole($name2, $description, $bizRule, $data);
$this->assertEquals($item2->type, Item::TYPE_ROLE);
// test adding an item with the same name
$this->setExpectedException('Exception');
$this->auth->createItem($name, $type, $description, $bizRule, $data);
}
public function testGetItem()
{
$this->assertTrue($this->auth->getItem('readPost') instanceof Item);
$this->assertTrue($this->auth->getItem('reader') instanceof Item);
$this->assertNull($this->auth->getItem('unknown'));
}
public function testRemoveAuthItem()
{
$this->assertTrue($this->auth->getItem('updatePost') instanceof Item);
$this->assertTrue($this->auth->removeItem('updatePost'));
$this->assertNull($this->auth->getItem('updatePost'));
$this->assertFalse($this->auth->removeItem('updatePost'));
}
public function testChangeItemName()
{
$item = $this->auth->getItem('readPost');
$this->assertTrue($item instanceof Item);
$this->assertTrue($this->auth->hasItemChild('reader', 'readPost'));
$item->name = 'readPost2';
$this->assertNull($this->auth->getItem('readPost'));
$this->assertEquals($this->auth->getItem('readPost2'), $item);
$this->assertFalse($this->auth->hasItemChild('reader', 'readPost'));
$this->assertTrue($this->auth->hasItemChild('reader', 'readPost2'));
}
public function testAddItemChild()
{
$this->auth->addItemChild('createPost', 'updatePost');
// test adding upper level item to lower one
$this->setExpectedException('Exception');
$this->auth->addItemChild('readPost', 'reader');
}
public function testAddItemChild2()
{
// test adding inexistent items
$this->setExpectedException('Exception');
$this->assertFalse($this->auth->addItemChild('createPost2', 'updatePost'));
}
public function testRemoveItemChild()
{
$this->assertTrue($this->auth->hasItemChild('reader', 'readPost'));
$this->assertTrue($this->auth->removeItemChild('reader', 'readPost'));
$this->assertFalse($this->auth->hasItemChild('reader', 'readPost'));
$this->assertFalse($this->auth->removeItemChild('reader', 'readPost'));
}
public function testGetItemChildren()
{
$this->assertEquals(array(), $this->auth->getItemChildren('readPost'));
$children = $this->auth->getItemChildren('author');
$this->assertEquals(3, count($children));
$this->assertTrue(reset($children) instanceof Item);
}
public function testAssign()
{
$auth = $this->auth->assign('new user', 'createPost', 'rule', 'data');
$this->assertTrue($auth instanceof Assignment);
$this->assertEquals($auth->userId, 'new user');
$this->assertEquals($auth->itemName, 'createPost');
$this->assertEquals($auth->bizRule, 'rule');
$this->assertEquals($auth->data, 'data');
$this->setExpectedException('Exception');
$this->auth->assign('new user', 'createPost2', 'rule', 'data');
}
public function testRevoke()
{
$this->assertTrue($this->auth->isAssigned('author B', 'author'));
$auth = $this->auth->getAssignment('author B', 'author');
$this->assertTrue($auth instanceof Assignment);
$this->assertTrue($this->auth->revoke('author B', 'author'));
$this->assertFalse($this->auth->isAssigned('author B', 'author'));
$this->assertFalse($this->auth->revoke('author B', 'author'));
}
public function testGetAssignments()
{
$this->auth->assign('author B', 'deletePost');
$auths = $this->auth->getAssignments('author B');
$this->assertEquals(2, count($auths));
$this->assertTrue(reset($auths) instanceof Assignment);
}
public function testGetItems()
{
$this->assertEquals(count($this->auth->getRoles()), 4);
$this->assertEquals(count($this->auth->getOperations()), 4);
$this->assertEquals(count($this->auth->getTasks()), 1);
$this->assertEquals(count($this->auth->getItems()), 9);
$this->assertEquals(count($this->auth->getItems('author B', null)), 1);
$this->assertEquals(count($this->auth->getItems('author C', null)), 0);
$this->assertEquals(count($this->auth->getItems('author B', Item::TYPE_ROLE)), 1);
$this->assertEquals(count($this->auth->getItems('author B', Item::TYPE_OPERATION)), 0);
}
public function testClearAll()
{
$this->auth->clearAll();
$this->assertEquals(count($this->auth->getRoles()), 0);
$this->assertEquals(count($this->auth->getOperations()), 0);
$this->assertEquals(count($this->auth->getTasks()), 0);
$this->assertEquals(count($this->auth->getItems()), 0);
$this->assertEquals(count($this->auth->getAssignments('author B')), 0);
}
public function testClearAssignments()
{
$this->auth->clearAssignments();
$this->assertEquals(count($this->auth->getAssignments('author B')), 0);
}
public function testDetectLoop()
{
$this->setExpectedException('Exception');
$this->auth->addItemChild('readPost', 'readPost');
}
public function testExecuteBizRule()
{
$this->assertTrue($this->auth->executeBizRule(null, array(), null));
$this->assertTrue($this->auth->executeBizRule('return 1==true;', array(), null));
$this->assertTrue($this->auth->executeBizRule('return $params[0]==$params[1];', array(1, '1'), null));
$this->assertFalse($this->auth->executeBizRule('invalid', array(), null));
}
public function testCheckAccess()
{
$results = array(
'reader A' => array(
'createPost' => false,
'readPost' => true,
'updatePost' => false,
'updateOwnPost' => false,
'deletePost' => false,
),
'author B' => array(
'createPost' => true,
'readPost' => true,
'updatePost' => true,
'updateOwnPost' => true,
'deletePost' => false,
),
'editor C' => array(
'createPost' => false,
'readPost' => true,
'updatePost' => true,
'updateOwnPost' => false,
'deletePost' => false,
),
'admin D' => array(
'createPost' => true,
'readPost' => true,
'updatePost' => true,
'updateOwnPost' => false,
'deletePost' => true,
),
);
$params = array('authorID' => 'author B');
foreach (array('reader A', 'author B', 'editor C', 'admin D') as $user) {
$params['userID'] = $user;
foreach (array('createPost', 'readPost', 'updatePost', 'updateOwnPost', 'deletePost') as $operation) {
$result = $this->auth->checkAccess($user, $operation, $params);
$this->assertEquals($results[$user][$operation], $result);
}
}
}
protected function prepareData()
{
$this->auth->createOperation('createPost', 'create a post');
$this->auth->createOperation('readPost', 'read a post');
$this->auth->createOperation('updatePost', 'update a post');
$this->auth->createOperation('deletePost', 'delete a post');
$task = $this->auth->createTask('updateOwnPost', 'update a post by author himself', 'return $params["authorID"]==$params["userID"];');
$task->addChild('updatePost');
$role = $this->auth->createRole('reader');
$role->addChild('readPost');
$role = $this->auth->createRole('author');
$role->addChild('reader');
$role->addChild('createPost');
$role->addChild('updateOwnPost');
$role = $this->auth->createRole('editor');
$role->addChild('reader');
$role->addChild('updatePost');
$role = $this->auth->createRole('admin');
$role->addChild('editor');
$role->addChild('author');
$role->addChild('deletePost');
$this->auth->assign('reader A', 'reader');
$this->auth->assign('author B', 'author');
$this->auth->assign('editor C', 'editor');
$this->auth->assign('admin D', 'admin');
}
}
<?php
namespace yiiunit\framework\rbac;
use Yii;
use yii\rbac\PhpManager;
require_once(__DIR__ . '/ManagerTestBase.php');
class PhpManagerTest extends ManagerTestBase
{
public function setUp()
{
$authFile = Yii::$app->getRuntimePath() . '/rbac.php';
@unlink($authFile);
$this->auth = new PhpManager;
$this->auth->authFile = $authFile;
$this->auth->init();
$this->prepareData();
}
public function tearDown()
{
@unlink($this->auth->authFile);
}
public function testSaveLoad()
{
$this->auth->save();
$this->auth->clearAll();
$this->auth->load();
$this->testCheckAccess();
}
}
......@@ -305,12 +305,12 @@ class Application extends Module
}
/**
* @return null|Component
* @todo
* Returns the auth manager for this application.
* @return \yii\rbac\Manager the auth manager for this application.
*/
public function getAuthManager()
{
return $this->getComponent('auth');
return $this->getComponent('authManager');
}
/**
......
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use Yii;
use yii\base\Object;
/**
* Assignment represents an assignment of a role to a user.
* It includes additional assignment information such as [[bizRule]] and [[data]].
* Do not create a Assignment instance using the 'new' operator.
* Instead, call [[Manager::assign()]].
*
* @property mixed $userId User ID (see [[User::id]]).
* @property string $itemName The authorization item name.
* @property string $bizRule The business rule associated with this assignment.
* @property mixed $data Additional data for this assignment.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class Assignment extends Object
{
private $_auth;
private $_userId;
private $_itemName;
private $_bizRule;
private $_data;
/**
* Constructor.
* @param Manager $auth the authorization manager
* @param mixed $userId user ID (see [[User::id]])
* @param string $itemName authorization item name
* @param string $bizRule the business rule associated with this assignment
* @param mixed $data additional data for this assignment
*/
public function __construct($auth, $userId, $itemName, $bizRule = null, $data = null)
{
$this->_auth = $auth;
$this->_userId = $userId;
$this->_itemName = $itemName;
$this->_bizRule = $bizRule;
$this->_data = $data;
}
/**
* @return mixed user ID (see [[User::id]])
*/
public function getUserId()
{
return $this->_userId;
}
/**
* @return string the authorization item name
*/
public function getItemName()
{
return $this->_itemName;
}
/**
* @return string the business rule associated with this assignment
*/
public function getBizRule()
{
return $this->_bizRule;
}
/**
* @param string $value the business rule associated with this assignment
*/
public function setBizRule($value)
{
if ($this->_bizRule !== $value) {
$this->_bizRule = $value;
$this->_auth->saveAssignment($this);
}
}
/**
* @return mixed additional data for this assignment
*/
public function getData()
{
return $this->_data;
}
/**
* @param mixed $value additional data for this assignment
*/
public function setData($value)
{
if ($this->_data !== $value) {
$this->_data = $value;
$this->_auth->saveAssignment($this);
}
}
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
use Yii;
use yii\base\Object;
/**
* Item represents an authorization item.
* An authorization item can be an operation, a task or a role.
* They form an authorization hierarchy. Items on higher levels of the hierarchy
* inherit the permissions represented by items on lower levels.
* A user may be assigned one or several authorization items (called [[Assignment]] assignments).
* He can perform an operation only when it is among his assigned items.
*
* @property Manager $authManager The authorization manager.
* @property integer $type The authorization item type. This could be 0 (operation), 1 (task) or 2 (role).
* @property string $name The item name.
* @property string $description The item description.
* @property string $bizRule The business rule associated with this item.
* @property mixed $data The additional data associated with this item.
* @property array $children All child items of this item.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0
*/
class Item extends Object
{
const TYPE_OPERATION = 0;
const TYPE_TASK = 1;
const TYPE_ROLE = 2;
private $_auth;
private $_type;
private $_name;
private $_description;
private $_bizRule;
private $_data;
/**
* Constructor.
* @param Manager $auth authorization manager
* @param string $name authorization item name
* @param integer $type authorization item type. This can be 0 (operation), 1 (task) or 2 (role).
* @param string $description the description
* @param string $bizRule the business rule associated with this item
* @param mixed $data additional data for this item
*/
public function __construct($auth, $name, $type, $description = '', $bizRule = null, $data = null)
{
$this->_type = (int)$type;
$this->_auth = $auth;
$this->_name = $name;
$this->_description = $description;
$this->_bizRule = $bizRule;
$this->_data = $data;
}
/**
* Checks to see if the specified item is within the hierarchy starting from this item.
* This method is expected to be internally used by the actual implementations
* of the [[Manager::checkAccess()]].
* @param string $itemName the name of the item to be checked
* @param array $params the parameters to be passed to business rule evaluation
* @return boolean whether the specified item is within the hierarchy starting from this item.
*/
public function checkAccess($itemName, $params = array())
{
Yii::trace('Checking permission: ' . $this->_name, __METHOD__);
if ($this->_auth->executeBizRule($this->_bizRule, $params, $this->_data)) {
if ($this->_name == $itemName) {
return true;
}
foreach ($this->_auth->getItemChildren($this->_name) as $item) {
if ($item->checkAccess($itemName, $params)) {
return true;
}
}
}
return false;
}
/**
* @return Manager the authorization manager
*/
public function getManager()
{
return $this->_auth;
}
/**
* @return integer the authorization item type. This could be 0 (operation), 1 (task) or 2 (role).
*/
public function getType()
{
return $this->_type;
}
/**
* @return string the item name
*/
public function getName()
{
return $this->_name;
}
/**
* @param string $value the item name
*/
public function setName($value)
{
if ($this->_name !== $value) {
$oldName = $this->_name;
$this->_name = $value;
$this->_auth->saveItem($this, $oldName);
}
}
/**
* @return string the item description
*/
public function getDescription()
{
return $this->_description;
}
/**
* @param string $value the item description
*/
public function setDescription($value)
{
if ($this->_description !== $value) {
$this->_description = $value;
$this->_auth->saveItem($this);
}
}
/**
* @return string the business rule associated with this item
*/
public function getBizRule()
{
return $this->_bizRule;
}
/**
* @param string $value the business rule associated with this item
*/
public function setBizRule($value)
{
if ($this->_bizRule !== $value) {
$this->_bizRule = $value;
$this->_auth->saveItem($this);
}
}
/**
* @return mixed the additional data associated with this item
*/
public function getData()
{
return $this->_data;
}
/**
* @param mixed $value the additional data associated with this item
*/
public function setData($value)
{
if ($this->_data !== $value) {
$this->_data = $value;
$this->_auth->saveItem($this);
}
}
/**
* Adds a child item.
* @param string $name the name of the child item
* @return boolean whether the item is added successfully
* @throws \yii\base\Exception if either parent or child doesn't exist or if a loop has been detected.
* @see Manager::addItemChild
*/
public function addChild($name)
{
return $this->_auth->addItemChild($this->_name, $name);
}
/**
* Removes a child item.
* Note, the child item is not deleted. Only the parent-child relationship is removed.
* @param string $name the child item name
* @return boolean whether the removal is successful
* @see Manager::removeItemChild
*/
public function removeChild($name)
{
return $this->_auth->removeItemChild($this->_name, $name);
}
/**
* Returns a value indicating whether a child exists
* @param string $name the child item name
* @return boolean whether the child exists
* @see Manager::hasItemChild
*/
public function hasChild($name)
{
return $this->_auth->hasItemChild($this->_name, $name);
}
/**
* Returns the children of this item.
* @return Item[] all child items of this item.
* @see Manager::getItemChildren
*/
public function getChildren()
{
return $this->_auth->getItemChildren($this->_name);
}
/**
* Assigns this item to a user.
* @param mixed $userId the user ID (see [[User::id]])
* @param string $bizRule the business rule to be executed when [[checkAccess()]] is called
* for this particular authorization item.
* @param mixed $data additional data associated with this assignment
* @return Assignment the authorization assignment information.
* @throws \yii\base\Exception if the item has already been assigned to the user
* @see Manager::assign
*/
public function assign($userId, $bizRule = null, $data = null)
{
return $this->_auth->assign($userId, $this->_name, $bizRule, $data);
}
/**
* Revokes an authorization assignment from a user.
* @param mixed $userId the user ID (see [[User::id]])
* @return boolean whether removal is successful
* @see Manager::revoke
*/
public function revoke($userId)
{
return $this->_auth->revoke($userId, $this->_name);
}
/**
* Returns a value indicating whether this item has been assigned to the user.
* @param mixed $userId the user ID (see [[User::id]])
* @return boolean whether the item has been assigned to the user.
* @see Manager::isAssigned
*/
public function isAssigned($userId)
{
return $this->_auth->isAssigned($userId, $this->_name);
}
/**
* Returns the item assignment information.
* @param mixed $userId the user ID (see [[User::id]])
* @return Assignment the item assignment information. Null is returned if
* this item is not assigned to the user.
* @see Manager::getAssignment
*/
public function getAssignment($userId)
{
return $this->_auth->getAssignment($userId, $this->_name);
}
}
......@@ -40,11 +40,11 @@ class User extends Component
*/
public $enableAutoLogin = false;
/**
* @var string|array the URL for login when [[loginRequired()]] is called.
* @var string|array the URL for login when [[loginRequired()]] is called.
* If an array is given, [[UrlManager::createUrl()]] will be called to create the corresponding URL.
* The first element of the array should be the route to the login action, and the rest of
* The first element of the array should be the route to the login action, and the rest of
* the name-value pairs are GET parameters used to construct the login URL. For example,
*
*
* ~~~
* array('site/login', 'ref' => 1)
* ~~~
......@@ -86,6 +86,8 @@ class User extends Component
*/
public $returnUrlVar = '__returnUrl';
private $_access = array();
/**
* Initializes the application component.
......@@ -449,19 +451,33 @@ class User extends Component
}
/**
* Checks whether the user has access to the specified operation.
* @param $operator
* @param array $params
* @return bool
* @todo
* Performs access check for this user.
* @param string $operation the name of the operation that need access check.
* @param array $params name-value pairs that would be passed to business rules associated
* with the tasks and roles assigned to the user. A param with name 'userId' is added to
* this array, which holds the value of [[id]] when [[DbAuthManager]] or
* [[PhpAuthManager]] is used.
* @param boolean $allowCaching whether to allow caching the result of access check.
* When this parameter is true (default), if the access check of an operation was performed
* before, its result will be directly returned when calling this method to check the same
* operation. If this parameter is false, this method will always call
* [[AuthManager::checkAccess()]] to obtain the up-to-date access result. Note that this
* caching is effective only within the same request and only works when `$params = array()`.
* @return boolean whether the operations can be performed by this user.
*/
public function checkAccess($operation, $params = array())
public function checkAccess($operation, $params = array(), $allowCaching = true)
{
$auth = Yii::$app->getAuthManager();
if ($auth !== null) {
return $auth->checkAccess($this->getId(), $operation, $params);
} else {
if ($auth === null) {
return false;
}
if ($allowCaching && empty($params) && isset($this->_access[$operation])) {
return $this->_access[$operation];
}
$access = $auth->checkAccess($this->getId(), $operation, $params);
if ($allowCaching && empty($params)) {
$this->_access[$operation] = $access;
}
return $access;
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment