DbManager.php 21.4 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\InvalidCallException;
15
use yii\base\InvalidParamException;
16
use yii\di\Instance;
17 18

/**
19 20
 * DbManager represents an authorization manager that stores authorization information in database.
 *
21 22 23
 * The database connection is specified by [[db]]. The database schema could be initialized by applying migration:
 *
 * ```
24
 * yii migrate --migrationPath=@yii/rbac/migrations/
25 26
 * ```
 *
27 28
 * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
 *
29
 * You may change the names of the three tables used to store the authorization data by setting [[itemTable]],
30 31
 * [[itemChildTable]] and [[assignmentTable]].
 *
32 33 34 35
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @since 2.0
 */
36
class DbManager extends BaseManager
37
{
38
    /**
39
     * @var Connection|array|string the DB connection object or the application component ID of the DB connection.
40 41
     * After the DbManager object is created, if you want to change this property, you should only assign it
     * with a DB connection object.
42
     * Starting from version 2.0.2, this can also be a configuration array for creating the object.
43 44 45
     */
    public $db = 'db';
    /**
46
     * @var string the name of the table storing authorization items. Defaults to "auth_item".
47 48 49
     */
    public $itemTable = '{{%auth_item}}';
    /**
50
     * @var string the name of the table storing authorization item hierarchy. Defaults to "auth_item_child".
51 52 53
     */
    public $itemChildTable = '{{%auth_item_child}}';
    /**
54
     * @var string the name of the table storing authorization item assignments. Defaults to "auth_assignment".
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

    /**
     * Initializes the application component.
     * This method overrides the parent implementation by establishing the database connection.
     */
    public function init()
    {
        parent::init();
70
        $this->db = Instance::ensure($this->db, Connection::className());
71 72 73
    }

    /**
74
     * @inheritdoc
75
     */
76
    public function checkAccess($userId, $permissionName, $params = [])
77 78
    {
        $assignments = $this->getAssignments($userId);
79
        return $this->checkAccessRecursive($userId, $permissionName, $params, $assignments);
80 81 82 83 84
    }

    /**
     * Performs access check for the specified user.
     * This method is internally called by [[checkAccess()]].
85
     * @param string|integer $user the user ID. This should can be either an integer or a string representing
86 87
     * the unique identifier of a user. See [[\yii\web\User::id]].
     * @param string $itemName the name of the operation that need access check
88
     * @param array $params name-value pairs that would be passed to rules associated
89
     * with the tasks and roles assigned to the user. A param with name 'user' is added to this array,
90 91 92
     * 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.
93
     */
94
    protected function checkAccessRecursive($user, $itemName, $params, $assignments)
95 96 97 98
    {
        if (($item = $this->getItem($itemName)) === null) {
            return false;
        }
99 100 101

        Yii::trace($item instanceof Role ? "Checking role: $itemName" : "Checking permission: $itemName", __METHOD__);

102
        if (!$this->executeRule($user, $item, $params)) {
103 104 105
            return false;
        }

106
        if (isset($assignments[$itemName]) || in_array($itemName, $this->defaultRoles)) {
107
            return true;
108
        }
109 110 111 112 113 114 115 116

        $query = new Query;
        $parents = $query->select(['parent'])
            ->from($this->itemChildTable)
            ->where(['child' => $itemName])
            ->column($this->db);
        foreach ($parents as $parent) {
            if ($this->checkAccessRecursive($user, $parent, $params, $assignments)) {
117 118 119 120 121 122 123 124
                return true;
            }
        }

        return false;
    }

    /**
125
     * @inheritdoc
126
     */
127
    protected function getItem($name)
128
    {
129 130 131 132 133 134
        $row = (new Query)->from($this->itemTable)
            ->where(['name' => $name])
            ->one($this->db);

        if ($row === false) {
            return null;
135 136
        }

137
        if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
Alexander Makarov committed
138
            $row['data'] = null;
139
        }
140 141

        return $this->populateItem($row);
142 143 144
    }

    /**
145 146 147
     * Returns a value indicating whether the database supports cascading update and delete.
     * The default implementation will return false for SQLite database and true for all other databases.
     * @return boolean whether the database supports cascading update and delete.
148
     */
149
    protected function supportsCascadeUpdate()
150
    {
151
        return strncmp($this->db->getDriverName(), 'sqlite', 6) !== 0;
152 153 154
    }

    /**
155
     * @inheritdoc
156
     */
157
    protected function addItem($item)
158
    {
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
        $time = time();
        if ($item->createdAt === null) {
            $item->createdAt = $time;
        }
        if ($item->updatedAt === null) {
            $item->updatedAt = $time;
        }
        $this->db->createCommand()
            ->insert($this->itemTable, [
                'name' => $item->name,
                'type' => $item->type,
                'description' => $item->description,
                'rule_name' => $item->ruleName,
                'data' => $item->data === null ? null : serialize($item->data),
                'created_at' => $item->createdAt,
                'updated_at' => $item->updatedAt,
            ])->execute();
176

177
        return true;
178 179 180
    }

    /**
181
     * @inheritdoc
182
     */
183
    protected function removeItem($item)
184
    {
185 186
        if (!$this->supportsCascadeUpdate()) {
            $this->db->createCommand()
187
                ->delete($this->itemChildTable, ['or', '[[parent]]=:name', '[[child]]=:name'], [':name' => $item->name])
188 189 190 191
                ->execute();
            $this->db->createCommand()
                ->delete($this->assignmentTable, ['item_name' => $item->name])
                ->execute();
192 193
        }

194 195 196 197 198
        $this->db->createCommand()
            ->delete($this->itemTable, ['name' => $item->name])
            ->execute();

        return true;
199 200 201
    }

    /**
202
     * @inheritdoc
203
     */
204
    protected function updateItem($name, $item)
205
    {
206 207 208 209 210 211 212 213 214 215
        if (!$this->supportsCascadeUpdate() && $item->name !== $name) {
            $this->db->createCommand()
                ->update($this->itemChildTable, ['parent' => $item->name], ['parent' => $name])
                ->execute();
            $this->db->createCommand()
                ->update($this->itemChildTable, ['child' => $item->name], ['child' => $name])
                ->execute();
            $this->db->createCommand()
                ->update($this->assignmentTable, ['item_name' => $item->name], ['item_name' => $name])
                ->execute();
216
        }
217 218 219

        $item->updatedAt = time();

220
        $this->db->createCommand()
221 222 223 224 225 226 227 228 229
            ->update($this->itemTable, [
                'name' => $item->name,
                'description' => $item->description,
                'rule_name' => $item->ruleName,
                'data' => $item->data === null ? null : serialize($item->data),
                'updated_at' => $item->updatedAt,
            ], [
                'name' => $name,
            ])->execute();
230

231
        return true;
232 233 234
    }

    /**
235
     * @inheritdoc
236
     */
237
    protected function addRule($rule)
238
    {
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
        $time = time();
        if ($rule->createdAt === null) {
            $rule->createdAt = $time;
        }
        if ($rule->updatedAt === null) {
            $rule->updatedAt = $time;
        }
        $this->db->createCommand()
            ->insert($this->ruleTable, [
                'name' => $rule->name,
                'data' => serialize($rule),
                'created_at' => $rule->createdAt,
                'updated_at' => $rule->updatedAt,
            ])->execute();

        return true;
255 256 257
    }

    /**
258
     * @inheritdoc
259
     */
260
    protected function updateRule($name, $rule)
261
    {
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        if (!$this->supportsCascadeUpdate() && $rule->name !== $name) {
            $this->db->createCommand()
                ->update($this->itemTable, ['rule_name' => $rule->name], ['rule_name' => $name])
                ->execute();
        }

        $rule->updatedAt = time();

        $this->db->createCommand()
            ->update($this->ruleTable, [
                'name' => $rule->name,
                'data' => serialize($rule),
                'updated_at' => $rule->updatedAt,
            ], [
                'name' => $name,
            ])->execute();

        return true;
280 281 282
    }

    /**
283
     * @inheritdoc
284
     */
285
    protected function removeRule($rule)
286
    {
287 288
        if (!$this->supportsCascadeUpdate()) {
            $this->db->createCommand()
289
                ->update($this->itemTable, ['rule_name' => null], ['rule_name' => $rule->name])
290 291
                ->execute();
        }
292

293 294 295 296 297
        $this->db->createCommand()
            ->delete($this->ruleTable, ['name' => $rule->name])
            ->execute();

        return true;
298 299 300
    }

    /**
301
     * @inheritdoc
302
     */
303
    protected function getItems($type)
304
    {
305 306 307
        $query = (new Query)
            ->from($this->itemTable)
            ->where(['type' => $type]);
308

309 310 311
        $items = [];
        foreach ($query->all($this->db) as $row) {
            $items[$row['name']] = $this->populateItem($row);
312
        }
313 314

        return $items;
315 316 317
    }

    /**
318 319 320
     * Populates an auth item with the data fetched from database
     * @param array $row the data from the auth item table
     * @return Item the populated auth item instance (either Role or Permission)
321
     */
322
    protected function populateItem($row)
323
    {
324 325 326 327
        $class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();

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

330 331 332 333 334 335 336 337 338
        return new $class([
            'name' => $row['name'],
            'type' => $row['type'],
            'description' => $row['description'],
            'ruleName' => $row['rule_name'],
            'data' => $data,
            'createdAt' => $row['created_at'],
            'updatedAt' => $row['updated_at'],
        ]);
339 340 341
    }

    /**
342
     * @inheritdoc
343
     */
344
    public function getRolesByUser($userId)
345
    {
346 347 348 349
        if (empty($userId)) {
            return [];
        }

350 351
        $query = (new Query)->select('b.*')
            ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
352
            ->where('{{a}}.[[item_name]]={{b}}.[[name]]')
Alexander Mohorev committed
353
            ->andWhere(['a.user_id' => (string) $userId]);
354 355 356 357 358 359

        $roles = [];
        foreach ($query->all($this->db) as $row) {
            $roles[$row['name']] = $this->populateItem($row);
        }
        return $roles;
360 361 362
    }

    /**
363
     * @inheritdoc
364
     */
365
    public function getPermissionsByRole($roleName)
366
    {
367 368 369 370 371
        $childrenList = $this->getChildrenList();
        $result = [];
        $this->getChildrenRecursive($roleName, $childrenList, $result);
        if (empty($result)) {
            return [];
372
        }
373
        $query = (new Query)->from($this->itemTable)->where([
374
            'type' => Item::TYPE_PERMISSION,
375 376 377 378 379 380 381 382
            'name' => array_keys($result),
        ]);
        $permissions = [];
        foreach ($query->all($this->db) as $row) {
            $permissions[$row['name']] = $this->populateItem($row);
        }
        return $permissions;
    }
383

384 385 386 387 388
    /**
     * @inheritdoc
     */
    public function getPermissionsByUser($userId)
    {
389 390 391 392
        if (empty($userId)) {
            return [];
        }

393 394
        $query = (new Query)->select('item_name')
            ->from($this->assignmentTable)
Alexander Mohorev committed
395
            ->where(['user_id' => (string) $userId]);
396 397 398 399 400 401

        $childrenList = $this->getChildrenList();
        $result = [];
        foreach ($query->column($this->db) as $roleName) {
            $this->getChildrenRecursive($roleName, $childrenList, $result);
        }
402

403 404 405
        if (empty($result)) {
            return [];
        }
406

407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
        $query = (new Query)->from($this->itemTable)->where([
            'type' => Item::TYPE_PERMISSION,
            'name' => array_keys($result),
        ]);
        $permissions = [];
        foreach ($query->all($this->db) as $row) {
            $permissions[$row['name']] = $this->populateItem($row);
        }
        return $permissions;
    }

    /**
     * Returns the children for every parent.
     * @return array the children list. Each array key is a parent item name,
     * and the corresponding array value is a list of child item names.
     */
    protected function getChildrenList()
    {
        $query = (new Query)->from($this->itemChildTable);
        $parents = [];
        foreach ($query->all($this->db) as $row) {
            $parents[$row['parent']][] = $row['child'];
        }
        return $parents;
    }

    /**
     * Recursively finds all children and grand children of the specified item.
     * @param string $name the name of the item whose children are to be looked for.
     * @param array $childrenList the child list built via [[getChildrenList()]]
     * @param array $result the children and grand children (in array keys)
     */
    protected function getChildrenRecursive($name, $childrenList, &$result)
    {
        if (isset($childrenList[$name])) {
            foreach ($childrenList[$name] as $child) {
                $result[$child] = true;
                $this->getChildrenRecursive($child, $childrenList, $result);
445 446
            }
        }
447
    }
448

449 450 451 452 453 454 455 456 457 458
    /**
     * @inheritdoc
     */
    public function getRule($name)
    {
        $row = (new Query)->select(['data'])
            ->from($this->ruleTable)
            ->where(['name' => $name])
            ->one($this->db);
        return $row === false ? null : unserialize($row['data']);
459 460 461
    }

    /**
462 463 464
     * @inheritdoc
     */
    public function getRules()
465
    {
466
        $query = (new Query)->from($this->ruleTable);
467

468 469 470 471 472 473
        $rules = [];
        foreach ($query->all($this->db) as $row) {
            $rules[$row['name']] = unserialize($row['data']);
        }

        return $rules;
474 475 476
    }

    /**
477
     * @inheritdoc
478
     */
479
    public function getAssignment($roleName, $userId)
480
    {
481 482 483 484
        if (empty($userId)) {
            return null;
        }

485
        $row = (new Query)->from($this->assignmentTable)
Alexander Mohorev committed
486
            ->where(['user_id' => (string) $userId, 'item_name' => $roleName])
487 488 489 490
            ->one($this->db);

        if ($row === false) {
            return null;
491 492
        }

493 494 495 496 497
        return new Assignment([
            'userId' => $row['user_id'],
            'roleName' => $row['item_name'],
            'createdAt' => $row['created_at'],
        ]);
498 499 500
    }

    /**
501
     * @inheritdoc
502
     */
503
    public function getAssignments($userId)
504
    {
505 506 507 508
        if (empty($userId)) {
            return [];
        }

509 510
        $query = (new Query)
            ->from($this->assignmentTable)
Alexander Mohorev committed
511
            ->where(['user_id' => (string) $userId]);
512

513 514 515 516 517 518
        $assignments = [];
        foreach ($query->all($this->db) as $row) {
            $assignments[$row['item_name']] = new Assignment([
                'userId' => $row['user_id'],
                'roleName' => $row['item_name'],
                'createdAt' => $row['created_at'],
519 520
            ]);
        }
521 522

        return $assignments;
523 524 525
    }

    /**
526
     * @inheritdoc
527
     */
528
    public function addChild($parent, $child)
529
    {
530 531 532 533 534 535 536 537 538 539
        if ($parent->name === $child->name) {
            throw new InvalidParamException("Cannot add '{$parent->name}' as a child of itself.");
        }

        if ($parent instanceof Permission && $child instanceof Role) {
            throw new InvalidParamException("Cannot add a role as a child of a permission.");
        }

        if ($this->detectLoop($parent, $child)) {
            throw new InvalidCallException("Cannot add '{$child->name}' as a child of '{$parent->name}'. A loop has been detected.");
540 541 542
        }

        $this->db->createCommand()
543
            ->insert($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
544 545
            ->execute();

546
        return true;
547 548 549
    }

    /**
550
     * @inheritdoc
551
     */
552
    public function removeChild($parent, $child)
553
    {
554 555 556
        return $this->db->createCommand()
            ->delete($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
            ->execute() > 0;
557 558
    }

559 560 561 562 563 564 565 566 567 568
    /**
     * @inheritdoc
     */
    public function removeChildren($parent)
    {
        return $this->db->createCommand()
            ->delete($this->itemChildTable, ['parent' => $parent->name])
            ->execute() > 0;
    }

569 570 571 572 573 574 575
    /**
     * @inheritdoc
     */
    public function hasChild($parent, $child)
    {
        return (new Query)
            ->from($this->itemChildTable)
Qiang Xue committed
576
            ->where(['parent' => $parent->name, 'child' => $child->name])
577 578 579
            ->one($this->db) !== false;
    }

580
    /**
581
     * @inheritdoc
582
     */
583
    public function getChildren($name)
584
    {
585 586 587
        $query = (new Query)
            ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at'])
            ->from([$this->itemTable, $this->itemChildTable])
588
            ->where(['parent' => $name, 'name' => new Expression('[[child]]')]);
589 590 591 592 593 594 595

        $children = [];
        foreach ($query->all($this->db) as $row) {
            $children[$row['name']] = $this->populateItem($row);
        }

        return $children;
596 597 598 599
    }

    /**
     * Checks whether there is a loop in the authorization item hierarchy.
600 601
     * @param Item $parent the parent item
     * @param Item $child the child item to be added to the hierarchy
602 603
     * @return boolean whether a loop exists
     */
604
    protected function detectLoop($parent, $child)
605
    {
606
        if ($child->name === $parent->name) {
607 608
            return true;
        }
609 610
        foreach ($this->getChildren($child->name) as $grandchild) {
            if ($this->detectLoop($parent, $grandchild)) {
611 612 613 614 615 616 617
                return true;
            }
        }
        return false;
    }

    /**
618
     * @inheritdoc
619
     */
620
    public function assign($role, $userId)
621
    {
622 623 624 625 626
        $assignment = new Assignment([
            'userId' => $userId,
            'roleName' => $role->name,
            'createdAt' => time(),
        ]);
627

628 629 630 631 632 633 634 635
        $this->db->createCommand()
            ->insert($this->assignmentTable, [
                'user_id' => $assignment->userId,
                'item_name' => $assignment->roleName,
                'created_at' => $assignment->createdAt,
            ])->execute();

        return $assignment;
636 637 638
    }

    /**
639
     * @inheritdoc
640
     */
641
    public function revoke($role, $userId)
642
    {
643 644 645 646
        if (empty($userId)) {
            return false;
        }

647
        return $this->db->createCommand()
Alexander Mohorev committed
648
            ->delete($this->assignmentTable, ['user_id' => (string) $userId, 'item_name' => $role->name])
649
            ->execute() > 0;
650 651 652
    }

    /**
653
     * @inheritdoc
654
     */
655
    public function revokeAll($userId)
656
    {
657 658 659 660
        if (empty($userId)) {
            return false;
        }

661
        return $this->db->createCommand()
Alexander Mohorev committed
662
            ->delete($this->assignmentTable, ['user_id' => (string) $userId])
663
            ->execute() > 0;
664 665 666
    }

    /**
667
     * @inheritdoc
668
     */
669
    public function removeAll()
670
    {
671
        $this->removeAllAssignments();
672 673 674
        $this->db->createCommand()->delete($this->itemChildTable)->execute();
        $this->db->createCommand()->delete($this->itemTable)->execute();
        $this->db->createCommand()->delete($this->ruleTable)->execute();
675 676 677
    }

    /**
678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
     * @inheritdoc
     */
    public function removeAllPermissions()
    {
        $this->removeAllItems(Item::TYPE_PERMISSION);
    }

    /**
     * @inheritdoc
     */
    public function removeAllRoles()
    {
        $this->removeAllItems(Item::TYPE_ROLE);
    }

    /**
     * Removes all auth items of the specified type.
     * @param integer $type the auth item type (either Item::TYPE_PERMISSION or Item::TYPE_ROLE)
     */
    protected function removeAllItems($type)
    {
        if (!$this->supportsCascadeUpdate()) {
            $names = (new Query)
                ->select(['name'])
                ->from($this->itemTable)
                ->where(['type' => $type])
                ->column($this->db);
            if (empty($names)) {
                return;
            }
            $key = $type == Item::TYPE_PERMISSION ? 'child' : 'parent';
            $this->db->createCommand()
                ->delete($this->itemChildTable, [$key => $names])
                ->execute();
            $this->db->createCommand()
                ->delete($this->assignmentTable, ['item_name' => $names])
                ->execute();
        }
        $this->db->createCommand()
            ->delete($this->itemTable, ['type' => $type])
            ->execute();
    }

    /**
     * @inheritdoc
     */
    public function removeAllRules()
    {
        if (!$this->supportsCascadeUpdate()) {
            $this->db->createCommand()
                ->update($this->itemTable, ['ruleName' => null])
                ->execute();
        }

        $this->db->createCommand()->delete($this->ruleTable)->execute();
    }

    /**
     * @inheritdoc
737
     */
738
    public function removeAllAssignments()
739
    {
740
        $this->db->createCommand()->delete($this->assignmentTable)->execute();
741 742
    }
}