Commit 7bc52f32 by Qiang Xue

Re-implemented RBAC by following more closely to the original NIST RBAC model.…

Re-implemented RBAC by following more closely to the original NIST RBAC model. Dropped `yii\rbac\PhpManager`.
parent f7396fa0
...@@ -86,209 +86,3 @@ Role based access control (RBAC) ...@@ -86,209 +86,3 @@ Role based access control (RBAC)
Role based access control is very flexible approach to controlling access that is a perfect match for complex systems Role based access control is very flexible approach to controlling access that is a perfect match for complex systems
where permissions are customizable. where permissions are customizable.
### Using file-based config for RBAC
In order to start using it some extra steps are required. First of all we need to configure `authManager` application
component in application config file (`web.php` or `main.php` depending on template you've used):
```php
'authManager' => [
'class' => 'app\components\PhpManager',
'defaultRoles' => ['guest'],
],
```
Often use role is stored in the same database table as other user data. In this case we may defined it by creating our
own component (`app/components/PhpManager.php`):
```php
<?php
namespace app\components;
use Yii;
class PhpManager extends \yii\rbac\PhpManager
{
public function init()
{
parent::init();
if (!Yii::$app->user->isGuest) {
// we suppose that user's role is stored in identity
$this->assign(Yii::$app->user->identity->id, Yii::$app->user->identity->role);
}
}
}
```
Now create custom rule class:
```php
namespace app\rbac;
use yii\rbac\Rule;
use Yii;
class NotGuestRule extends Rule
{
public $name = 'notGuestRule';
public function execute($params, $data)
{
return !Yii::$app->user->isGuest;
}
}
```
Then create permissions hierarchy in `@app/data/rbac.php`:
```php
<?php
use yii\rbac\Item;
use app\rbac\NotGuestRule;
$notGuest = new NotGuestRule();
return [
'rules' => [
$notGuest->name => serialize($notGuest),
],
'items' => [
// HERE ARE YOUR MANAGEMENT TASKS
'manageThing0' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
'manageThing1' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
'manageThing2' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
'manageThing3' => ['type' => Item::TYPE_OPERATION, 'description' => '...', 'ruleName' => null, 'data' => null],
// AND THE ROLES
'guest' => [
'type' => Item::TYPE_ROLE,
'description' => 'Guest',
'ruleName' => null,
'data' => null
],
'user' => [
'type' => Item::TYPE_ROLE,
'description' => 'User',
'children' => [
'guest',
'manageThing0', // User can edit thing0
],
'ruleName' => $notGuest->name,
'data' => null
],
'moderator' => [
'type' => Item::TYPE_ROLE,
'description' => 'Moderator',
'children' => [
'user', // Can manage all that user can
'manageThing1', // and also thing1
],
'ruleName' => null,
'data' => null
],
'admin' => [
'type' => Item::TYPE_ROLE,
'description' => 'Admin',
'children' => [
'moderator', // can do all the stuff that moderator can
'manageThing2', // and also manage thing2
],
'ruleName' => null,
'data' => null
],
'godmode' => [
'type' => Item::TYPE_ROLE,
'description' => 'Super admin',
'children' => [
'admin', // can do all that admin can
'manageThing3', // and also thing3
],
'ruleName' => null,
'data' => null
],
],
];
```
Now you can specify roles from RBAC in controller's access control configuration:
```php
public function behaviors()
{
return [
'access' => [
'class' => 'yii\filters\AccessControl',
'except' => ['something'],
'rules' => [
[
'allow' => true,
'roles' => ['manageThing1'],
],
],
],
];
}
```
Another way is to call [[yii\web\User::checkAccess()]] where appropriate.
### Using DB-based storage for RBAC
Storing RBAC hierarchy in database is less efficient performancewise but is much more flexible. It is easier to create
a good management UI for it so in case you need permissions structure that is managed by end user DB is your choice.
In order to get started you need to configure database connection in `db` component. After it is done [get `schema-*.sql`
file for your database](https://github.com/yiisoft/yii2/tree/master/framework/rbac) and execute it.
Next step is to configure `authManager` application component in application config file (`web.php` or `main.php`
depending on template you've used):
```php
'authManager' => [
'class' => 'yii\rbac\DbManager',
'defaultRoles' => ['guest'],
],
```
TBD
### How it works
TBD: write about how it works with pictures :)
### Avoiding too much RBAC
In order to keep auth hierarchy simple and efficient you should avoid creating and using too much nodes. Most of the time
simple checks could be used instead. For example such code that uses RBAC:
```php
public function editArticle($id)
{
$article = Article::findOne($id);
if (!$article) {
throw new NotFoundHttpException;
}
if (!\Yii::$app->user->checkAccess('edit_article', ['article' => $article])) {
throw new ForbiddenHttpException;
}
// ...
}
```
can be replaced with simpler code that doesn't use RBAC:
```php
public function editArticle($id)
{
$article = Article::findOne(['id' => $id, 'author_id' => \Yii::$app->user->id]);
if (!$article) {
throw new NotFoundHttpException;
}
// ...
}
```
...@@ -282,6 +282,7 @@ Yii Framework 2 Change Log ...@@ -282,6 +282,7 @@ Yii Framework 2 Change Log
- Chg: `yii\log\Logger` is split into `yii\log\Logger` and `yii\log\Dispatcher`. (qiangxue) - Chg: `yii\log\Logger` is split into `yii\log\Logger` and `yii\log\Dispatcher`. (qiangxue)
- Chg: Moved all filter classes to namespace `yii\filters` (qiangxue) - Chg: Moved all filter classes to namespace `yii\filters` (qiangxue)
- Chg: Removed `Application::preload` in favor of `Application::bootstrap` (qiangxue) - Chg: Removed `Application::preload` in favor of `Application::bootstrap` (qiangxue)
- Chg: Re-implemented RBAC by following more closely to the original NIST RBAC model. Dropped `yii\rbac\PhpManager`. (qiangxue)
- New #66: [Auth client library](https://github.com/yiisoft/yii2-authclient) OpenId, OAuth1, OAuth2 clients (klimov-paul) - New #66: [Auth client library](https://github.com/yiisoft/yii2-authclient) OpenId, OAuth1, OAuth2 clients (klimov-paul)
- New #303: Added built-in support for REST API (qiangxue) - New #303: Added built-in support for REST API (qiangxue)
- New #503: Added `yii\di\Container` and `yii\di\ServiceLocator` (qiangxue) - New #503: Added `yii\di\Container` and `yii\di\ServiceLocator` (qiangxue)
......
...@@ -12,9 +12,8 @@ use yii\base\Object; ...@@ -12,9 +12,8 @@ use yii\base\Object;
/** /**
* Assignment represents an assignment of a role to a user. * Assignment represents an assignment of a role to a user.
* It includes additional assignment information such as [[ruleName]] and [[data]]. *
* Do not create a Assignment instance using the 'new' operator. * It includes additional assignment information including [[ruleName]] and [[data]].
* Instead, call [[Manager::assign()]].
* *
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com> * @author Alexander Kochetov <creocoder@gmail.com>
...@@ -23,33 +22,15 @@ use yii\base\Object; ...@@ -23,33 +22,15 @@ use yii\base\Object;
class Assignment extends Object class Assignment extends Object
{ {
/** /**
* @var Manager the auth manager of this item * @var string|integer user ID (see [[\yii\web\User::id]])
*/
public $manager;
/**
* @var string name of the rule associated with this assignment
*/
public $ruleName;
/**
* @var mixed additional data for this assignment
*/
public $data;
/**
* @var mixed user ID (see [[\yii\web\User::id]]). Do not modify this property after it is populated.
* To modify the user ID of an assignment, you must remove the assignment and create a new one.
*/ */
public $userId; public $userId;
/** /**
* @return string the authorization item name. Do not modify this property after it is populated. * @return string the role name
* To modify the item name of an assignment, you must remove the assignment and create a new one.
*/ */
public $itemName; public $roleName;
/** /**
* Saves the changes to an authorization assignment. * @var integer UNIX timestamp representing the assignment creation time
*/ */
public function save() public $createdAt;
{
$this->manager->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\base\Component;
use yii\base\InvalidConfigException;
use yii\base\InvalidParamException;
/**
* BaseManager is a base class implementing [[ManagerInterface]] for RBAC management.
*
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
abstract class BaseManager extends Component implements ManagerInterface
{
/**
* @var array a list of role names that are assigned to every user automatically without calling [[assign()]].
*/
public $defaultRoles = [];
/**
* Returns the named auth item.
* @param string $name the auth item name.
* @return Item the auth item corresponding to the specified name. Null is returned if no such item.
*/
abstract protected function getItem($name);
/**
* Returns the items of the specified type.
* @param integer $type the auth item type (either [[Item::TYPE_ROLE]] or [[Item::TYPE_PERMISSION]]
* @return Item[] the auth items of the specified type.
*/
abstract protected function getItems($type);
/**
* Adds an auth item to the RBAC system.
* @param Item $item
* @return boolean whether the auth item is successfully added to the system
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
abstract protected function addItem($item);
/**
* Adds a rule to the RBAC system.
* @param Rule $rule
* @return boolean whether the rule is successfully added to the system
* @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
*/
abstract protected function addRule($rule);
/**
* Removes an auth item from the RBAC system.
* @param Item $item
* @return boolean whether the role or permission is successfully removed
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
abstract protected function removeItem($item);
/**
* Removes a rule from the RBAC system.
* @param Rule $rule
* @return boolean whether the rule is successfully removed
* @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
*/
abstract protected function removeRule($rule);
/**
* Updates an auth item in the RBAC system.
* @param string $name the old name of the auth item
* @param Item $item
* @return boolean whether the auth item is successfully updated
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
abstract protected function updateItem($name, $item);
/**
* Updates a rule to the RBAC system.
* @param string $name the old name of the rule
* @param Rule $rule
* @return boolean whether the rule is successfully updated
* @throws \Exception if data validation or saving fails (such as the name of the rule is not unique)
*/
abstract protected function updateRule($name, $rule);
/**
* @inheritdoc
*/
public function createRole($name)
{
$role = new Role;
$role->name = $name;
return $role;
}
/**
* @inheritdoc
*/
public function createPermission($name)
{
$permission = new Permission();
$permission->name = $name;
return $permission;
}
/**
* @inheritdoc
*/
public function add($object)
{
if ($object instanceof Item) {
return $this->addItem($object);
} elseif ($object instanceof Rule) {
return $this->addRule($object);
} else {
throw new InvalidParamException("Adding unsupported object type.");
}
}
/**
* @inheritdoc
*/
public function remove($object)
{
if ($object instanceof Item) {
return $this->removeItem($object);
} elseif ($object instanceof Rule) {
return $this->removeRule($object);
} else {
throw new InvalidParamException("Removing unsupported object type.");
}
}
/**
* @inheritdoc
*/
public function update($name, $object)
{
if ($object instanceof Item) {
return $this->updateItem($name, $object);
} elseif ($object instanceof Rule) {
return $this->updateRule($name, $object);
} else {
throw new InvalidParamException("Updating unsupported object type.");
}
}
/**
* @inheritdoc
*/
public function getRole($name)
{
$item = $this->getItem($name);
return $item instanceof Item && $item->type == Item::TYPE_ROLE ? $item : null;
}
/**
* @inheritdoc
*/
public function getPermission($name)
{
$item = $this->getItem($name);
return $item instanceof Item && $item->type == Item::TYPE_PERMISSION ? $item : null;
}
/**
* @inheritdoc
*/
public function getRoles()
{
return $this->getItems(Item::TYPE_ROLE);
}
/**
* @inheritdoc
*/
public function getPermissions()
{
return $this->getItems(Item::TYPE_PERMISSION);
}
/**
* Executes the rule associated with the specified auth item.
*
* If the item does not specify a rule, this method will return true. Otherwise, it will
* return the value of [[Rule::execute()]].
*
* @param Item $item the auth item that needs to execute its rule
* @param array $params parameters passed to [[ManagerInterface::checkAccess()]] and will be passed to the rule
* @return boolean the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned.
* @throws InvalidConfigException if the auth item has an invalid rule.
*/
protected function executeRule($item, $params)
{
if ($item->ruleName === null) {
return true;
}
$rule = $this->getRule($item->ruleName);
if ($rule instanceof Rule) {
return $rule->execute($item, $params);
} else {
throw new InvalidConfigException("Rule not found: {$item->ruleName}");
}
}
}
...@@ -7,34 +7,25 @@ ...@@ -7,34 +7,25 @@
namespace yii\rbac; namespace yii\rbac;
use Yii;
use yii\base\Object; 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 Item[] $children All child items of this item. This property is read-only.
* @property string $name The item name.
*
* @author Qiang Xue <qiang.xue@gmail.com> * @author Qiang Xue <qiang.xue@gmail.com>
* @author Alexander Kochetov <creocoder@gmail.com>
* @since 2.0 * @since 2.0
*/ */
class Item extends Object class Item extends Object
{ {
const TYPE_OPERATION = 0; const TYPE_ROLE = 1;
const TYPE_TASK = 1; const TYPE_PERMISSION = 2;
const TYPE_ROLE = 2;
/** /**
* @var Manager the auth manager of this item * @var integer the type of the item. This should be either [[TYPE_ROLE]] or [[TYPE_PERMISSION]].
*/ */
public $manager; public $type;
/**
* @var string the name of the item. This must be globally unique.
*/
public $name;
/** /**
* @var string the item description * @var string the item description
*/ */
...@@ -48,158 +39,11 @@ class Item extends Object ...@@ -48,158 +39,11 @@ class Item extends Object
*/ */
public $data; public $data;
/** /**
* @var integer the authorization item type. This could be 0 (operation), 1 (task) or 2 (role). * @var integer UNIX timestamp representing the item creation time
*/
public $type;
private $_name;
private $_oldName;
/**
* 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 = [])
{
Yii::trace('Checking permission: ' . $this->_name, __METHOD__);
if ($this->manager->executeRule($this->ruleName, $params, $this->data)) {
if ($this->_name == $itemName) {
return true;
}
foreach ($this->manager->getItemChildren($this->_name) as $item) {
if ($item->checkAccess($itemName, $params)) {
return true;
}
}
}
return false;
}
/**
* @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) {
$this->_oldName = $this->_name;
$this->_name = $value;
}
}
/**
* 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->manager->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->manager->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->manager->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->manager->getItemChildren($this->_name);
}
/**
* Assigns this item to a user.
*
* @param mixed $userId the user ID (see [[\yii\web\User::id]])
* @param Rule $rule the 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, Rule $rule = null, $data = null) public $createdAt;
{
return $this->manager->assign($userId, $this->_name, $rule, $data);
}
/**
* Revokes an authorization assignment from a user.
* @param mixed $userId the user ID (see [[\yii\web\User::id]])
* @return boolean whether removal is successful
* @see Manager::revoke
*/
public function revoke($userId)
{
return $this->manager->revoke($userId, $this->_name);
}
/**
* Returns a value indicating whether this item has been assigned to the user.
* @param mixed $userId the user ID (see [[\yii\web\User::id]])
* @return boolean whether the item has been assigned to the user.
* @see Manager::isAssigned
*/
public function isAssigned($userId)
{
return $this->manager->isAssigned($userId, $this->_name);
}
/**
* Returns the item assignment information.
* @param mixed $userId the user ID (see [[\yii\web\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->manager->getAssignment($userId, $this->_name);
}
/** /**
* Saves an authorization item to persistent storage. * @var integer UNIX timestamp representing the item updating time
*/ */
public function save() public $updatedAt;
{
$this->manager->saveItem($this, $this->_oldName);
$this->_oldName = null;
}
} }
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
interface ManagerInterface
{
/**
* Checks if the user has the specified permission.
* @param string|integer $userId the user ID. This should be either an integer or a string representing
* the unique identifier of a user. See [[\yii\web\User::id]].
* @param string $permissionName the name of the permission to be checked against
* @param array $params name-value pairs that will be passed to the rules associated
* with the roles and permissions assigned to the user.
* @return boolean whether the user has the specified permission.
* @throws \yii\base\InvalidParamException if $permissionName does not refer to an existing permission
*/
public function checkAccess($userId, $permissionName, $params = []);
/**
* Creates a new Role object.
* Note that the newly created role is not added to the RBAC system yet.
* You must fill in the needed data and call [[add()]] to add it to the system.
* @param string $name the role name
* @return Role the new Role object
*/
public function createRole($name);
/**
* Creates a new Permission object.
* Note that the newly created permission is not added to the RBAC system yet.
* You must fill in the needed data and call [[add()]] to add it to the system.
* @param string $name the permission name
* @return Permission the new Permission object
*/
public function createPermission($name);
/**
* Adds a role, permission or rule to the RBAC system.
* @param Role|Permission|Rule $object
* @return boolean whether the role, permission or rule is successfully added to the system
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
public function add($object);
/**
* Removes a role, permission or rule from the RBAC system.
* @param Role|Permission|Rule $object
* @return boolean whether the role, permission or rule is successfully removed
*/
public function remove($object);
/**
* Updates the specified role, permission or rule in the system.
* @param string $name the old name of the role, permission or rule
* @param Role|Permission|Rule $object
* @return boolean whether the update is successful
* @throws \Exception if data validation or saving fails (such as the name of the role or permission is not unique)
*/
public function update($name, $object);
/**
* Returns the named role.
* @param string $name the role name.
* @return Role the role corresponding to the specified name. Null is returned if no such role.
*/
public function getRole($name);
/**
* Returns all roles in the system.
* @return Role[] all roles in the system. The array is indexed by the role names.
*/
public function getRoles();
/**
* Returns the roles that are assigned to the user via [[assign()]].
* Note that child roles that are not assigned directly to the user will not be returned.
* @param string|integer $userId the user ID (see [[\yii\web\User::id]])
* @return Role[] all roles directly or indirectly assigned to the user. The array is indexed by the role names.
*/
public function getRolesByUser($userId);
/**
* Returns the named permission.
* @param string $name the permission name.
* @return Permission the permission corresponding to the specified name. Null is returned if no such permission.
*/
public function getPermission($name);
/**
* Returns all permissions in the system.
* @return Permission[] all permissions in the system. The array is indexed by the permission names.
*/
public function getPermissions();
/**
* Returns all permissions that the specified role represents.
* @param string $roleName the role name
* @return Permission[] all permissions that the role represents. The array is indexed by the permission names.
*/
public function getPermissionsByRole($roleName);
/**
* Returns all permissions that the user has.
* @param string|integer $userId the user ID (see [[\yii\web\User::id]])
* @return Permission[] all permissions that the user has. The array is indexed by the permission names.
*/
public function getPermissionsByUser($userId);
/**
* Returns the rule of the specified name.
* @param string $name the rule name
* @return Rule the rule object, or null if the specified name does not correspond to a rule.
*/
public function getRule($name);
/**
* Returns all rules available in the system.
* @return Rule[] the rules indexed by the rule names
*/
public function getRules();
/**
* Adds an item as a child of another item.
* @param Item $parent
* @param Item $child
* @throws \yii\base\Exception if the parent-child relationship already exists or if a loop has been detected.
*/
public function addChild($parent, $child);
/**
* Removes a child from its parent.
* Note, the child item is not deleted. Only the parent-child relationship is removed.
* @param Item $parent
* @param Item $child
* @return boolean whether the removal is successful
*/
public function removeChild($parent, $child);
/**
* Returns the child permissions and/or roles.
* @param string $name the parent name
* @return Item[] the child permissions and/or roles
*/
public function getChildren($name);
/**
* Assigns a role to a user.
*
* @param Role $role
* @param string|integer $userId the user ID (see [[\yii\web\User::id]])
* @param Rule $rule the rule to be associated with this assignment. If not null, the rule
* will be executed when [[allow()]] is called to check the user permission.
* @param mixed $data additional data associated with this assignment.
* @return Assignment the role assignment information.
* @throws \Exception if the role has already been assigned to the user
*/
public function assign($role, $userId, $rule = null, $data = null);
/**
* Revokes a role from a user.
* @param Role $role
* @param string|integer $userId the user ID (see [[\yii\web\User::id]])
* @return boolean whether the revoking is successful
*/
public function revoke($role, $userId);
/**
* Revokes all roles from a user.
* @param mixed $userId the user ID (see [[\yii\web\User::id]])
* @return boolean whether the revoking is successful
*/
public function revokeAll($userId);
/**
* Returns the assignment information regarding a role and a user.
* @param string|integer $userId the user ID (see [[\yii\web\User::id]])
* @param string $roleName the role name
* @return Assignment the assignment information. Null is returned if
* the role is not assigned to the user.
*/
public function getAssignment($roleName, $userId);
/**
* Returns all role assignment information for the specified user.
* @param string|integer $userId the user ID (see [[\yii\web\User::id]])
* @return Assignment[] the assignments indexed by role names. An empty array will be
* returned if there is no role assigned to the user.
*/
public function getAssignments($userId);
/**
* Removes all authorization data.
*/
public function clearAll();
/**
* Removes all authorization assignments.
*/
public function clearAssignments();
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Permission extends Item
{
/**
* @inheritdoc
*/
public $type = self::TYPE_PERMISSION;
}
<?php
/**
* @link http://www.yiiframework.com/
* @copyright Copyright (c) 2008 Yii Software LLC
* @license http://www.yiiframework.com/license/
*/
namespace yii\rbac;
/**
* @author Qiang Xue <qiang.xue@gmail.com>
* @since 2.0
*/
class Role extends Item
{
/**
* @inheritdoc
*/
public $type = self::TYPE_ROLE;
}
...@@ -10,8 +10,7 @@ namespace yii\rbac; ...@@ -10,8 +10,7 @@ namespace yii\rbac;
use yii\base\Object; use yii\base\Object;
/** /**
* Rule represents a business constraint that may be assigned and the applied to * Rule represents a business constraint that may be associated with a role, permission or assignment.
* an authorization item or assignment.
* *
* @author Alexander Makarov <sam@rmcreative.ru> * @author Alexander Makarov <sam@rmcreative.ru>
* @since 2.0 * @since 2.0
...@@ -22,13 +21,21 @@ abstract class Rule extends Object ...@@ -22,13 +21,21 @@ abstract class Rule extends Object
* @var string name of the rule * @var string name of the rule
*/ */
public $name; public $name;
/**
* @var integer UNIX timestamp representing the rule creation time
*/
public $createdAt;
/**
* @var integer UNIX timestamp representing the rule updating time
*/
public $updatedAt;
/** /**
* Executes the rule. * Executes the rule.
* *
* @param array $params parameters passed to [[Manager::checkAccess()]]. * @param Item $item the auth item that this rule is associated with
* @param mixed $data additional data associated with the authorization item or assignment. * @param array $params parameters passed to [[ManagerInterface::allow()]].
* @return boolean whether the rule execution returns true. * @return boolean a value indicating whether the rule permits the auth item it is associated with.
*/ */
abstract public function execute($params, $data); abstract public function execute($item, $params);
} }
...@@ -18,6 +18,8 @@ create table [auth_rule] ...@@ -18,6 +18,8 @@ create table [auth_rule]
( (
[name] varchar(64) not null, [name] varchar(64) not null,
[data] text, [data] text,
[created_at] integer,
[updated_at] integer,
primary key ([name]) primary key ([name])
); );
...@@ -28,6 +30,8 @@ create table [auth_item] ...@@ -28,6 +30,8 @@ create table [auth_item]
[description] text, [description] text,
[rule_name] varchar(64), [rule_name] varchar(64),
[data] text, [data] text,
[created_at] integer,
[updated_at] integer,
primary key ([name]), primary key ([name]),
foreign key ([rule_name]) references [auth_rule] ([name]) on delete set null on update cascade, foreign key ([rule_name]) references [auth_rule] ([name]) on delete set null on update cascade,
key [type] ([type]) key [type] ([type])
...@@ -46,9 +50,7 @@ create table [auth_assignment] ...@@ -46,9 +50,7 @@ create table [auth_assignment]
( (
[item_name] varchar(64) not null, [item_name] varchar(64) not null,
[user_id] varchar(64) not null, [user_id] varchar(64) not null,
[rule_name] varchar(64), [created_at] integer,
[data] text,
primary key ([item_name], [user_id]), primary key ([item_name], [user_id]),
foreign key ([item_name]) references [auth_item] ([name]) on delete cascade on update cascade, foreign key ([item_name]) references [auth_item] ([name]) on delete cascade on update cascade
foreign key ([rule_name]) references [auth_rule] ([name]) on delete set null on update cascade
); );
...@@ -18,6 +18,8 @@ create table `auth_rule` ...@@ -18,6 +18,8 @@ create table `auth_rule`
( (
`name` varchar(64) not null, `name` varchar(64) not null,
`data` text, `data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`) primary key (`name`)
) engine InnoDB; ) engine InnoDB;
...@@ -28,6 +30,8 @@ create table `auth_item` ...@@ -28,6 +30,8 @@ create table `auth_item`
`description` text, `description` text,
`rule_name` varchar(64), `rule_name` varchar(64),
`data` text, `data` text,
`created_at` integer,
`updated_at` integer,
primary key (`name`), primary key (`name`),
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade, foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade,
key `type` (`type`) key `type` (`type`)
...@@ -46,9 +50,7 @@ create table `auth_assignment` ...@@ -46,9 +50,7 @@ create table `auth_assignment`
( (
`item_name` varchar(64) not null, `item_name` varchar(64) not null,
`user_id` varchar(64) not null, `user_id` varchar(64) not null,
`rule_name` varchar(64), `created_at` integer,
`data` text,
primary key (`item_name`, `user_id`), primary key (`item_name`, `user_id`),
foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade, foreign key (`item_name`) references `auth_item` (`name`) on delete cascade on update cascade
foreign key (`rule_name`) references `auth_rule` (`name`) on delete set null on update cascade
) engine InnoDB; ) engine InnoDB;
...@@ -18,6 +18,8 @@ create table "auth_rule" ...@@ -18,6 +18,8 @@ create table "auth_rule"
( (
"name" varchar(64) not null, "name" varchar(64) not null,
"data" text, "data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name") primary key ("name")
); );
...@@ -28,6 +30,8 @@ create table "auth_item" ...@@ -28,6 +30,8 @@ create table "auth_item"
"description" text, "description" text,
"rule_name" varchar(64), "rule_name" varchar(64),
"data" text, "data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name"), primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade, foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade,
key "type" ("type") key "type" ("type")
...@@ -46,9 +50,7 @@ create table "auth_assignment" ...@@ -46,9 +50,7 @@ create table "auth_assignment"
( (
"item_name" varchar(64) not null, "item_name" varchar(64) not null,
"user_id" varchar(64) not null, "user_id" varchar(64) not null,
"rule_name" varchar(64), "created_at" integer,
"data" text,
primary key ("item_name","user_id"), primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade, foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
); );
...@@ -18,6 +18,8 @@ create table "auth_rule" ...@@ -18,6 +18,8 @@ create table "auth_rule"
( (
"name" varchar(64) not null, "name" varchar(64) not null,
"data" text, "data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name") primary key ("name")
); );
...@@ -28,6 +30,8 @@ create table "auth_item" ...@@ -28,6 +30,8 @@ create table "auth_item"
"description" text, "description" text,
"rule_name" varchar(64), "rule_name" varchar(64),
"data" text, "data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name"), primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
); );
...@@ -47,9 +51,7 @@ create table "auth_assignment" ...@@ -47,9 +51,7 @@ create table "auth_assignment"
( (
"item_name" varchar(64) not null, "item_name" varchar(64) not null,
"user_id" varchar(64) not null, "user_id" varchar(64) not null,
"rule_name" varchar(64), "created_at" integer,
"data" text,
primary key ("item_name","user_id"), primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade, foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
); );
...@@ -18,6 +18,8 @@ create table "auth_rule" ...@@ -18,6 +18,8 @@ create table "auth_rule"
( (
"name" varchar(64) not null, "name" varchar(64) not null,
"data" text, "data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name") primary key ("name")
); );
...@@ -28,6 +30,8 @@ create table "auth_item" ...@@ -28,6 +30,8 @@ create table "auth_item"
"description" text, "description" text,
"rule_name" varchar(64), "rule_name" varchar(64),
"data" text, "data" text,
"created_at" integer,
"updated_at" integer,
primary key ("name"), primary key ("name"),
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
); );
...@@ -47,9 +51,7 @@ create table "auth_assignment" ...@@ -47,9 +51,7 @@ create table "auth_assignment"
( (
"item_name" varchar(64) not null, "item_name" varchar(64) not null,
"user_id" varchar(64) not null, "user_id" varchar(64) not null,
"rule_name" varchar(64), "created_at" integer,
"data" text,
primary key ("item_name","user_id"), primary key ("item_name","user_id"),
foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade, foreign key ("item_name") references "auth_item" ("name") on delete cascade on update cascade
foreign key ("rule_name") references "auth_rule" ("name") on delete set null on update cascade
); );
...@@ -14,9 +14,8 @@ class AuthorRule extends Rule ...@@ -14,9 +14,8 @@ class AuthorRule extends Rule
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function execute($params, $data) public function execute($item, $params)
{ {
return $params['authorID'] == $params['userID']; return $params['authorID'] == $params['user'];
} }
} }
\ No newline at end of file
...@@ -29,8 +29,6 @@ abstract class DbManagerTestCase extends ManagerTestCase ...@@ -29,8 +29,6 @@ abstract class DbManagerTestCase extends ManagerTestCase
} }
$this->auth = new DbManager(['db' => $this->getConnection()]); $this->auth = new DbManager(['db' => $this->getConnection()]);
$this->auth->init();
$this->prepareData();
} }
protected function tearDown() protected function tearDown()
......
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