DbManager.php 19 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 21 22 23 24 25
 * 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]].
 *
26 27 28 29
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @since 2.0
 */
30
class DbManager extends BaseManager
31
{
32 33 34 35 36 37
    /**
     * @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';
38

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

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

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

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

59 60 61 62 63 64 65 66

    /**
     * Initializes the application component.
     * This method overrides the parent implementation by establishing the database connection.
     */
    public function init()
    {
        parent::init();
67

68
        $this->db = Instance::ensure($this->db, Connection::className());
69 70 71
    }

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

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

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

        if (!$this->executeRule($item, $params)) {
            return false;
        }

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

        $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)) {
118 119 120 121 122 123 124 125
                return true;
            }
        }

        return false;
    }

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

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

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

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

    /**
146 147 148
     * 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.
149
     */
150
    protected function supportsCascadeUpdate()
151
    {
152
        return strncmp($this->db->getDriverName(), 'sqlite', 6) !== 0;
153 154 155
    }

    /**
156
     * @inheritdoc
157
     */
158
    protected function addItem($item)
159
    {
160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
        $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();
177

178
        return true;
179 180 181
    }

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

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

        return true;
200 201 202
    }

    /**
203
     * @inheritdoc
204
     */
205
    protected function updateItem($name, $item)
206
    {
207 208 209 210 211 212 213 214 215 216
        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();
217
        }
218 219 220

        $item->updatedAt = time();

221
        $this->db->createCommand()
222 223 224 225 226 227 228 229 230
            ->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();
231

232
        return true;
233 234 235
    }

    /**
236
     * @inheritdoc
237
     */
238
    protected function addRule($rule)
239
    {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
        $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;
256 257 258
    }

    /**
259
     * @inheritdoc
260
     */
261
    protected function updateRule($name, $rule)
262
    {
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
        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;
281 282 283
    }

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

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

        return true;
299 300 301
    }

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

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

        return $items;
316 317 318
    }

    /**
319 320 321
     * 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)
322
     */
323
    protected function populateItem($row)
324
    {
325 326 327 328
        $class = $row['type'] == Item::TYPE_PERMISSION ? Permission::className() : Role::className();

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

331 332 333 334 335 336 337 338 339
        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'],
        ]);
340 341 342
    }

    /**
343
     * @inheritdoc
344
     */
345
    public function getRolesByUser($userId)
346
    {
347 348 349 350 351 352 353 354 355 356
        $query = (new Query)->select('b.*')
            ->from(['a' => $this->assignmentTable, 'b' => $this->itemTable])
            ->where('a.item_name=b.name')
            ->andWhere(['a.user_id' => $userId]);

        $roles = [];
        foreach ($query->all($this->db) as $row) {
            $roles[$row['name']] = $this->populateItem($row);
        }
        return $roles;
357 358 359
    }

    /**
360
     * @inheritdoc
361
     */
362
    public function getPermissionsByRole($roleName)
363
    {
364 365 366 367 368
        $childrenList = $this->getChildrenList();
        $result = [];
        $this->getChildrenRecursive($roleName, $childrenList, $result);
        if (empty($result)) {
            return [];
369
        }
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 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
        $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;
    }
    
    /**
     * @inheritdoc
     */
    public function getPermissionsByUser($userId)
    {
        $query = (new Query)->select('item_name')
            ->from($this->assignmentTable)
            ->where(['user_id' => $userId]);

        $childrenList = $this->getChildrenList();
        $result = [];
        foreach ($query->column($this->db) as $roleName) {
            $this->getChildrenRecursive($roleName, $childrenList, $result);
        }
        
        if (empty($result)) {
            return [];
        }
        
        $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);
438 439
            }
        }
440
    }
441

442 443 444 445 446 447 448 449 450 451
    /**
     * @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']);
452 453 454
    }

    /**
455 456 457
     * @inheritdoc
     */
    public function getRules()
458
    {
459
        $query = (new Query)->from($this->ruleTable);
460

461 462 463 464 465 466
        $rules = [];
        foreach ($query->all($this->db) as $row) {
            $rules[$row['name']] = unserialize($row['data']);
        }

        return $rules;
467 468 469
    }

    /**
470
     * @inheritdoc
471
     */
472
    public function getAssignment($roleName, $userId)
473
    {
474 475 476 477 478 479
        $row = (new Query)->from($this->assignmentTable)
            ->where(['user_id' => $userId, 'item_name' => $roleName])
            ->one($this->db);

        if ($row === false) {
            return null;
480 481
        }

482 483 484 485 486 487 488 489 490
        if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
            $data = null;
        }

        return new Assignment([
            'userId' => $row['user_id'],
            'roleName' => $row['item_name'],
            'createdAt' => $row['created_at'],
        ]);
491 492 493
    }

    /**
494
     * @inheritdoc
495
     */
496
    public function getAssignments($userId)
497
    {
498 499 500
        $query = (new Query)
            ->from($this->assignmentTable)
            ->where(['user_id' => $userId]);
501

502 503
        $assignments = [];
        foreach ($query->all($this->db) as $row) {
504 505 506
            if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
                $data = null;
            }
507 508 509 510
            $assignments[$row['item_name']] = new Assignment([
                'userId' => $row['user_id'],
                'roleName' => $row['item_name'],
                'createdAt' => $row['created_at'],
511 512
            ]);
        }
513 514

        return $assignments;
515 516 517
    }

    /**
518
     * @inheritdoc
519
     */
520
    public function addChild($parent, $child)
521
    {
522 523 524 525 526 527 528 529 530 531
        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.");
532 533 534
        }

        $this->db->createCommand()
535
            ->insert($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
536 537
            ->execute();

538
        return true;
539 540 541
    }

    /**
542
     * @inheritdoc
543
     */
544
    public function removeChild($parent, $child)
545
    {
546 547 548
        return $this->db->createCommand()
            ->delete($this->itemChildTable, ['parent' => $parent->name, 'child' => $child->name])
            ->execute() > 0;
549 550 551
    }

    /**
552
     * @inheritdoc
553
     */
554
    public function getChildren($name)
555
    {
556 557 558 559 560 561 562 563 564 565 566
        $query = (new Query)
            ->select(['name', 'type', 'description', 'rule_name', 'data', 'created_at', 'updated_at'])
            ->from([$this->itemTable, $this->itemChildTable])
            ->where(['parent' => $name, 'name' => new Expression('child')]);

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

        return $children;
567 568 569 570
    }

    /**
     * Checks whether there is a loop in the authorization item hierarchy.
571 572
     * @param Item $parent the parent item
     * @param Item $child the child item to be added to the hierarchy
573 574
     * @return boolean whether a loop exists
     */
575
    protected function detectLoop($parent, $child)
576
    {
577
        if ($child->name === $parent->name) {
578 579
            return true;
        }
580 581
        foreach ($this->getChildren($child->name) as $grandchild) {
            if ($this->detectLoop($parent, $grandchild)) {
582 583 584 585 586 587 588
                return true;
            }
        }
        return false;
    }

    /**
589
     * @inheritdoc
590
     */
591
    public function assign($role, $userId, $rule = null, $data = null)
592
    {
593 594 595 596 597
        $assignment = new Assignment([
            'userId' => $userId,
            'roleName' => $role->name,
            'createdAt' => time(),
        ]);
598

599 600 601 602 603 604 605 606
        $this->db->createCommand()
            ->insert($this->assignmentTable, [
                'user_id' => $assignment->userId,
                'item_name' => $assignment->roleName,
                'created_at' => $assignment->createdAt,
            ])->execute();

        return $assignment;
607 608 609
    }

    /**
610
     * @inheritdoc
611
     */
612
    public function revoke($role, $userId)
613
    {
614 615 616
        return $this->db->createCommand()
            ->delete($this->assignmentTable, ['user_id' => $userId, 'item_name' => $role->name])
            ->execute() > 0;
617 618 619
    }

    /**
620
     * @inheritdoc
621
     */
622
    public function revokeAll($userId)
623
    {
624 625 626
        return $this->db->createCommand()
            ->delete($this->assignmentTable, ['user_id' => $userId])
            ->execute() > 0;
627 628 629
    }

    /**
630
     * Removes all authorization data.
631
     */
632
    public function clearAll()
633
    {
634 635 636 637
        $this->clearAssignments();
        $this->db->createCommand()->delete($this->itemChildTable)->execute();
        $this->db->createCommand()->delete($this->itemTable)->execute();
        $this->db->createCommand()->delete($this->ruleTable)->execute();
638 639 640
    }

    /**
641
     * Removes all authorization assignments.
642
     */
643
    public function clearAssignments()
644
    {
645
        $this->db->createCommand()->delete($this->assignmentTable)->execute();
646 647
    }
}