DbManager.php 24.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
<?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\db\Connection;
use yii\db\Query;
13
use yii\db\Expression;
14
use yii\base\Exception;
15
use yii\base\InvalidCallException;
16
use yii\base\InvalidParamException;
17
use yii\di\Instance;
18 19

/**
20 21 22 23 24 25 26
 * DbManager represents an authorization manager that stores authorization information in database.
 *
 * The database connection is specified by [[db]]. And the database schema
 * should be as described in "framework/rbac/*.sql". You may change the names of
 * the three tables used to store the authorization data by setting [[itemTable]],
 * [[itemChildTable]] and [[assignmentTable]].
 *
27 28
 * @property Item[] $items The authorization items of the specific type. This property is read-only.
 *
29 30 31 32 33 34
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @since 2.0
 */
class DbManager extends Manager
{
35 36 37 38 39 40
    /**
     * @var Connection|string the DB connection object or the application component ID of the DB connection.
     * After the DbManager object is created, if you want to change this property, you should only assign it
     * with a DB connection object.
     */
    public $db = 'db';
41

42
    /**
43
     * @var string the name of the table storing authorization items. Defaults to "auth_item".
44 45
     */
    public $itemTable = '{{%auth_item}}';
46

47
    /**
48
     * @var string the name of the table storing authorization item hierarchy. Defaults to "auth_item_child".
49 50
     */
    public $itemChildTable = '{{%auth_item_child}}';
51

52
    /**
53
     * @var string the name of the table storing authorization item assignments. Defaults to "auth_assignment".
54 55 56
     */
    public $assignmentTable = '{{%auth_assignment}}';

57 58 59 60 61
    /**
     * @var string the name of the table storing rules. Defaults to "auth_rule".
     */
    public $ruleTable = '{{%auth_rule}}';

62 63 64 65 66 67 68 69 70
    private $_usingSqlite;

    /**
     * Initializes the application component.
     * This method overrides the parent implementation by establishing the database connection.
     */
    public function init()
    {
        parent::init();
71 72
        $this->db = Instance::ensure($this->db, Connection::className());
        $this->_usingSqlite = !strncmp($this->db->getDriverName(), 'sqlite', 6);
73 74 75 76
    }

    /**
     * Performs access check for the specified user.
77 78 79
     * @param mixed $userId the user ID. This should can be either an integer or a string representing
     * the unique identifier of a user. See [[\yii\web\User::id]].
     * @param string $itemName the name of the operation that need access check
80
     * @param array $params name-value pairs that would be passed to rules associated
81 82
     * with the tasks and roles assigned to the user. A param with name 'userId' is added to this array,
     * which holds the value of `$userId`.
83 84 85 86 87 88 89 90 91 92 93 94
     * @return boolean whether the operations can be performed by the user.
     */
    public function checkAccess($userId, $itemName, $params = [])
    {
        $assignments = $this->getAssignments($userId);

        return $this->checkAccessRecursive($userId, $itemName, $params, $assignments);
    }

    /**
     * Performs access check for the specified user.
     * This method is internally called by [[checkAccess()]].
95 96 97
     * @param mixed $userId the user ID. This should can be either an integer or a string representing
     * the unique identifier of a user. See [[\yii\web\User::id]].
     * @param string $itemName the name of the operation that need access check
98
     * @param array $params name-value pairs that would be passed to rules associated
99 100 101 102
     * with the tasks and roles assigned to the user. A param with name 'userId' is added to this array,
     * which holds the value of `$userId`.
     * @param Assignment[] $assignments the assignments to the specified user
     * @return boolean whether the operations can be performed by the user.
103 104 105 106 107 108 109 110 111 112
     */
    protected function checkAccessRecursive($userId, $itemName, $params, $assignments)
    {
        if (($item = $this->getItem($itemName)) === null) {
            return false;
        }
        Yii::trace('Checking permission: ' . $item->getName(), __METHOD__);
        if (!isset($params['userId'])) {
            $params['userId'] = $userId;
        }
113
        if ($this->executeRule($item->ruleName, $params, $item->data)) {
114 115 116 117 118
            if (in_array($itemName, $this->defaultRoles)) {
                return true;
            }
            if (isset($assignments[$itemName])) {
                $assignment = $assignments[$itemName];
119
                if ($this->executeRule($assignment->ruleName, $params, $assignment->data)) {
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
                    return true;
                }
            }
            $query = new Query;
            $parents = $query->select(['parent'])
                ->from($this->itemChildTable)
                ->where(['child' => $itemName])
                ->createCommand($this->db)
                ->queryColumn();
            foreach ($parents as $parent) {
                if ($this->checkAccessRecursive($userId, $parent, $params, $assignments)) {
                    return true;
                }
            }
        }

        return false;
    }

    /**
     * Adds an item as a child of another item.
141 142 143 144
     * @param string $itemName the parent item name
     * @param string $childName the child item name
     * @return boolean whether the item is added successfully
     * @throws Exception if either parent or child doesn't exist.
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
     * @throws InvalidCallException if a loop has been detected.
     */
    public function addItemChild($itemName, $childName)
    {
        if ($itemName === $childName) {
            throw new Exception("Cannot add '$itemName' as a child of itself.");
        }
        $query = new Query;
        $rows = $query->from($this->itemTable)
            ->where(['or', 'name=:name1', 'name=:name2'], [':name1' => $itemName, ':name2' => $childName])
            ->createCommand($this->db)
            ->queryAll();
        if (count($rows) == 2) {
            if ($rows[0]['name'] === $itemName) {
                $parentType = $rows[0]['type'];
                $childType = $rows[1]['type'];
            } else {
                $childType = $rows[0]['type'];
                $parentType = $rows[1]['type'];
            }
            $this->checkItemChildType($parentType, $childType);
            if ($this->detectLoop($itemName, $childName)) {
                throw new InvalidCallException("Cannot add '$childName' as a child of '$itemName'. A loop has been detected.");
            }
            $this->db->createCommand()
                ->insert($this->itemChildTable, ['parent' => $itemName, 'child' => $childName])
                ->execute();

            return true;
        } else {
            throw new Exception("Either '$itemName' or '$childName' does not exist.");
        }
    }

    /**
     * Removes a child from its parent.
     * Note, the child item is not deleted. Only the parent-child relationship is removed.
182 183
     * @param string $itemName the parent item name
     * @param string $childName the child item name
184 185 186 187 188 189 190 191 192 193 194
     * @return boolean whether the removal is successful
     */
    public function removeItemChild($itemName, $childName)
    {
        return $this->db->createCommand()
            ->delete($this->itemChildTable, ['parent' => $itemName, 'child' => $childName])
            ->execute() > 0;
    }

    /**
     * Returns a value indicating whether a child exists within a parent.
195 196
     * @param string $itemName the parent item name
     * @param string $childName the child item name
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
     * @return boolean whether the child exists
     */
    public function hasItemChild($itemName, $childName)
    {
        $query = new Query;

        return $query->select(['parent'])
            ->from($this->itemChildTable)
            ->where(['parent' => $itemName, 'child' => $childName])
            ->createCommand($this->db)
            ->queryScalar() !== false;
    }

    /**
     * Returns the children of the specified item.
212 213
     * @param mixed $names the parent item name. This can be either a string or an array.
     * The latter represents a list of item names.
214 215 216 217 218
     * @return Item[] all child items of the parent
     */
    public function getItemChildren($names)
    {
        $query = new Query;
219
        $rows = $query->select(['name', 'type', 'description', 'rule_name', 'data'])
220 221 222 223 224 225 226 227 228 229 230 231 232 233
            ->from([$this->itemTable, $this->itemChildTable])
            ->where(['parent' => $names, 'name' => new Expression('child')])
            ->createCommand($this->db)
            ->queryAll();
        $children = [];
        foreach ($rows as $row) {
            if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
                $data = null;
            }
            $children[$row['name']] = new Item([
                'manager' => $this,
                'name' => $row['name'],
                'type' => $row['type'],
                'description' => $row['description'],
234
                'ruleName' => $row['rule_name'],
235 236 237 238 239 240 241 242 243
                'data' => $data,
            ]);
        }

        return $children;
    }

    /**
     * Assigns an authorization item to a user.
244
     *
245
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
246
     * @param string $itemName the item name
247
     * @param string $ruleName the business rule to be executed when [[checkAccess()]] is called
248 249 250
     * for this particular authorization item.
     * @param mixed $data additional data associated with this assignment
     * @return Assignment the authorization assignment information.
251 252
     * @throws InvalidParamException if the item does not exist or if the item has already been assigned to the user
     */
253
    public function assign($userId, $itemName, $ruleName = null, $data = null)
254 255 256 257 258 259 260 261
    {
        if ($this->usingSqlite() && $this->getItem($itemName) === null) {
            throw new InvalidParamException("The item '$itemName' does not exist.");
        }
        $this->db->createCommand()
            ->insert($this->assignmentTable, [
                'user_id' => $userId,
                'item_name' => $itemName,
262
                'rule_name' => $ruleName,
263 264 265 266 267 268 269 270
                'data' => $data === null ? null : serialize($data),
            ])
            ->execute();

        return new Assignment([
            'manager' => $this,
            'userId' => $userId,
            'itemName' => $itemName,
271
            'ruleName' => $ruleName,
272 273 274 275 276 277
            'data' => $data,
        ]);
    }

    /**
     * Revokes an authorization assignment from a user.
278 279
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
     * @param string $itemName the item name
280 281 282 283 284 285 286 287 288 289 290
     * @return boolean whether removal is successful
     */
    public function revoke($userId, $itemName)
    {
        return $this->db->createCommand()
            ->delete($this->assignmentTable, ['user_id' => $userId, 'item_name' => $itemName])
            ->execute() > 0;
    }

    /**
     * Revokes all authorization assignments from a user.
291
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
292 293 294 295 296 297 298 299 300 301 302
     * @return boolean whether removal is successful
     */
    public function revokeAll($userId)
    {
        return $this->db->createCommand()
                        ->delete($this->assignmentTable, ['user_id' => $userId])
                        ->execute() > 0;
    }

    /**
     * Returns a value indicating whether the item has been assigned to the user.
303 304
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
     * @param string $itemName the item name
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
     * @return boolean whether the item has been assigned to the user.
     */
    public function isAssigned($userId, $itemName)
    {
        $query = new Query;

        return $query->select(['item_name'])
            ->from($this->assignmentTable)
            ->where(['user_id' => $userId, 'item_name' => $itemName])
            ->createCommand($this->db)
            ->queryScalar() !== false;
    }

    /**
     * Returns the item assignment information.
320 321
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
     * @param string $itemName the item name
322
     * @return Assignment the item assignment information. Null is returned if
323
     * the item is not assigned to the user.
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
     */
    public function getAssignment($userId, $itemName)
    {
        $query = new Query;
        $row = $query->from($this->assignmentTable)
            ->where(['user_id' => $userId, 'item_name' => $itemName])
            ->createCommand($this->db)
            ->queryOne();
        if ($row !== false) {
            if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
                $data = null;
            }

            return new Assignment([
                'manager' => $this,
                'userId' => $row['user_id'],
                'itemName' => $row['item_name'],
341
                'ruleName' => $row['rule_name'],
342 343 344 345 346 347 348 349 350
                'data' => $data,
            ]);
        } else {
            return null;
        }
    }

    /**
     * Returns the item assignments for the specified user.
351
     * @param mixed $userId the user ID (see [[\yii\web\User::id]])
352
     * @return Assignment[] the item assignment information for the user. An empty array will be
353
     * returned if there is no item assigned to the user.
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
     */
    public function getAssignments($userId)
    {
        $query = new Query;
        $rows = $query->from($this->assignmentTable)
            ->where(['user_id' => $userId])
            ->createCommand($this->db)
            ->queryAll();
        $assignments = [];
        foreach ($rows as $row) {
            if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
                $data = null;
            }
            $assignments[$row['item_name']] = new Assignment([
                'manager' => $this,
                'userId' => $row['user_id'],
                'itemName' => $row['item_name'],
371
                'ruleName' => $row['rule_name'],
372 373 374 375 376 377 378 379 380 381 382
                'data' => $data,
            ]);
        }

        return $assignments;
    }

    /**
     * Saves the changes to an authorization assignment.
     * @param Assignment $assignment the assignment that has been changed.
     */
383
    public function saveAssignment(Assignment $assignment)
384 385 386
    {
        $this->db->createCommand()
            ->update($this->assignmentTable, [
387
                'rule_name' => $assignment->ruleName,
388 389 390 391 392 393 394 395 396 397
                'data' => $assignment->data === null ? null : serialize($assignment->data),
            ], [
                'user_id' => $assignment->userId,
                'item_name' => $assignment->itemName,
            ])
            ->execute();
    }

    /**
     * Returns the authorization items of the specific type and user.
398 399 400 401 402
     * @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
     * they are not assigned to a user.
     * @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
     * meaning returning all items regardless of their type.
     * @return Item[] the authorization items of the specific type.
403 404 405 406 407 408 409 410 411 412 413 414
     */
    public function getItems($userId = null, $type = null)
    {
        $query = new Query;
        if ($userId === null && $type === null) {
            $command = $query->from($this->itemTable)
                ->createCommand($this->db);
        } elseif ($userId === null) {
            $command = $query->from($this->itemTable)
                ->where(['type' => $type])
                ->createCommand($this->db);
        } elseif ($type === null) {
415
            $command = $query->select(['name', 'type', 'description', 't1.rule_name', 't1.data'])
416 417 418 419
                ->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2'])
                ->where(['user_id' => $userId, 'name' => new Expression('item_name')])
                ->createCommand($this->db);
        } else {
420
            $command = $query->select(['name', 'type', 'description', 't1.rule_name', 't1.data'])
421 422 423 424 425 426 427 428 429 430 431 432 433 434
                ->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2'])
                ->where(['user_id' => $userId, 'type' => $type, 'name' => new Expression('item_name')])
                ->createCommand($this->db);
        }
        $items = [];
        foreach ($command->queryAll() as $row) {
            if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
                $data = null;
            }
            $items[$row['name']] = new Item([
                'manager' => $this,
                'name' => $row['name'],
                'type' => $row['type'],
                'description' => $row['description'],
435
                'ruleName' => $row['rule_name'],
436 437 438 439 440 441 442 443 444 445 446 447 448
                'data' => $data,
            ]);
        }

        return $items;
    }

    /**
     * Creates an authorization item.
     * An authorization item represents an action permission (e.g. creating a post).
     * It has three types: operation, task and role.
     * Authorization items form a hierarchy. Higher level items inheirt permissions representing
     * by lower level items.
449
     *
450 451 452
     * @param string $name the item name. This must be a unique identifier.
     * @param integer $type the item type (0: operation, 1: task, 2: role).
     * @param string $description description of the item
453
     * @param string $rule business rule associated with the item. This is a piece of
454 455 456
     * PHP code that will be executed when [[checkAccess()]] is called for the item.
     * @param mixed $data additional data associated with the item.
     * @return Item the authorization item
457 458
     * @throws Exception if an item with the same name already exists
     */
459
    public function createItem($name, $type, $description = '', $rule = null, $data = null)
460 461 462 463 464 465
    {
        $this->db->createCommand()
            ->insert($this->itemTable, [
                'name' => $name,
                'type' => $type,
                'description' => $description,
466
                'rule_name' => $rule,
467 468 469 470 471 472 473 474 475
                'data' => $data === null ? null : serialize($data),
            ])
            ->execute();

        return new Item([
            'manager' => $this,
            'name' => $name,
            'type' => $type,
            'description' => $description,
476
            'ruleName' => $rule,
477 478 479 480 481 482
            'data' => $data,
        ]);
    }

    /**
     * Removes the specified authorization item.
483
     * @param string $name the name of the item to be removed
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503
     * @return boolean whether the item exists in the storage and has been removed
     */
    public function removeItem($name)
    {
        if ($this->usingSqlite()) {
            $this->db->createCommand()
                ->delete($this->itemChildTable, ['or', 'parent=:name', 'child=:name'], [':name' => $name])
                ->execute();
            $this->db->createCommand()
                ->delete($this->assignmentTable, ['item_name' => $name])
                ->execute();
        }

        return $this->db->createCommand()
            ->delete($this->itemTable, ['name' => $name])
            ->execute() > 0;
    }

    /**
     * Returns the authorization item with the specified name.
504 505
     * @param string $name the name of the item
     * @return Item the authorization item. Null if the item cannot be found.
506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
     */
    public function getItem($name)
    {
        $query = new Query;
        $row = $query->from($this->itemTable)
            ->where(['name' => $name])
            ->createCommand($this->db)
            ->queryOne();

        if ($row !== false) {
            if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
                $data = null;
            }

            return new Item([
                'manager' => $this,
                'name' => $row['name'],
                'type' => $row['type'],
                'description' => $row['description'],
525
                'ruleName' => $row['rule_name'],
526 527 528 529 530 531 532 533 534
                'data' => $data,
            ]);
        } else {
            return null;
        }
    }

    /**
     * Saves an authorization item to persistent storage.
535
     * @param Item $item the item to be saved.
536 537
     * @param string $oldName the old item name. If null, it means the item name is not changed.
     */
538
    public function saveItem(Item $item, $oldName = null)
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
    {
        if ($this->usingSqlite() && $oldName !== null && $item->getName() !== $oldName) {
            $this->db->createCommand()
                ->update($this->itemChildTable, ['parent' => $item->getName()], ['parent' => $oldName])
                ->execute();
            $this->db->createCommand()
                ->update($this->itemChildTable, ['child' => $item->getName()], ['child' => $oldName])
                ->execute();
            $this->db->createCommand()
                ->update($this->assignmentTable, ['item_name' => $item->getName()], ['item_name' => $oldName])
                ->execute();
        }

        $this->db->createCommand()
            ->update($this->itemTable, [
                'name' => $item->getName(),
                'type' => $item->type,
                'description' => $item->description,
557
                'rule_name' => $item->ruleName,
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
                'data' => $item->data === null ? null : serialize($item->data),
            ], [
                'name' => $oldName === null ? $item->getName() : $oldName,
            ])
            ->execute();
    }

    /**
     * Saves the authorization data to persistent storage.
     */
    public function save()
    {
    }

    /**
     * Removes all authorization data.
     */
    public function clearAll()
    {
        $this->clearAssignments();
        $this->db->createCommand()->delete($this->itemChildTable)->execute();
        $this->db->createCommand()->delete($this->itemTable)->execute();
    }

    /**
     * Removes all authorization assignments.
     */
    public function clearAssignments()
    {
        $this->db->createCommand()->delete($this->assignmentTable)->execute();
    }

    /**
     * Checks whether there is a loop in the authorization item hierarchy.
592 593
     * @param string $itemName parent item name
     * @param string $childName the name of the child item that is to be added to the hierarchy
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
     * @return boolean whether a loop exists
     */
    protected function detectLoop($itemName, $childName)
    {
        if ($childName === $itemName) {
            return true;
        }
        foreach ($this->getItemChildren($childName) as $child) {
            if ($this->detectLoop($itemName, $child->getName())) {
                return true;
            }
        }

        return false;
    }

    /**
     * @return boolean whether the database is a SQLite database
     */
    protected function usingSqlite()
    {
        return $this->_usingSqlite;
    }
617 618 619 620 621 622 623 624 625

    /**
     * Removes the specified rule.
     *
     * @param string $name the name of the rule to be removed
     * @return boolean whether the rule exists in the storage and has been removed
     */
    public function removeRule($name)
    {
626
        return $this->db->createCommand()->delete($this->ruleTable, ['name' => $name])->execute();
627 628 629 630 631 632 633
    }

    /**
     * Saves the changes to the rule.
     *
     * @param Rule $rule the rule that has been changed.
     */
634
    public function insertRule(Rule $rule)
635
    {
636 637 638 639 640 641 642 643 644 645 646 647
        $this->db->createCommand()->insert($this->ruleTable, ['name' => $rule->name, 'data' => serialize($rule)])->execute();
    }

    /**
     * Updates existing rule.
     *
     * @param string $name the name of the rule to update
     * @param Rule $rule new rule
     */
    public function updateRule($name, Rule $rule)
    {
        $this->db->createCommand()->update($this->ruleTable, ['name' => $rule->name, 'data' => serialize($rule)], ['name' => $name])->execute();
648 649 650 651 652 653 654 655 656 657
    }

    /**
     * Returns rule given its name.
     *
     * @param string $name name of the rule.
     * @return Rule
     */
    public function getRule($name)
    {
658 659 660 661
        $query = new Query;
        $query->select(['data'])->from($this->ruleTable)->where(['name' => $name]);
        $row = $query->createCommand($this->db)->queryOne();
        return $row === false ? null : unserialize($row['data']);
662 663 664 665 666 667 668 669 670
    }

    /**
     * Returns all rules.
     *
     * @return Rule[]
     */
    public function getRules()
    {
671 672 673 674 675 676 677 678 679 680
        $query = new Query();
        $rows = $query->from($this->ruleTable)->createCommand($this->db)->queryAll();

        $rules = [];
        foreach ($rows as $row) {
            $rules[$row['name']] = unserialize($row['data']);
        }
        return $rules;
    }
}