DbManager.php 19.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 15
use yii\base\Exception;
use yii\base\InvalidConfigException;
16
use yii\base\InvalidCallException;
17
use yii\base\InvalidParamException;
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 35 36 37 38 39 40 41 42 43
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @author Alexander Kochetov <creocoder@gmail.com>
 * @since 2.0
 */
class DbManager extends Manager
{
	/**
	 * @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';
	/**
	 * @var string the name of the table storing authorization items. Defaults to 'tbl_auth_item'.
	 */
44
	public $itemTable = '{{%auth_item}}';
45 46 47
	/**
	 * @var string the name of the table storing authorization item hierarchy. Defaults to 'tbl_auth_item_child'.
	 */
Carsten Brandt committed
48
	public $itemChildTable = '{{%auth_item_child}}';
49 50 51
	/**
	 * @var string the name of the table storing authorization item assignments. Defaults to 'tbl_auth_assignment'.
	 */
52
	public $assignmentTable = '{{%auth_assignment}}';
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

	private $_usingSqlite;

	/**
	 * Initializes the application component.
	 * This method overrides the parent implementation by establishing the database connection.
	 */
	public function init()
	{
		if (is_string($this->db)) {
			$this->db = Yii::$app->getComponent($this->db);
		}
		if (!$this->db instanceof Connection) {
			throw new InvalidConfigException("DbManager::db must be either a DB connection instance or the application component ID of a DB connection.");
		}
		$this->_usingSqlite = !strncmp($this->db->getDriverName(), 'sqlite', 6);
		parent::init();
	}

	/**
	 * Performs access check for the specified user.
74
	 * @param mixed $userId the user ID. This should can be either an integer or a string representing
75
	 * the unique identifier of a user. See [[User::id]].
76
	 * @param string $itemName the name of the operation that need access check
77 78 79 80 81
	 * @param array $params name-value pairs that would be passed to biz rules associated
	 * with the tasks and roles assigned to the user. A param with name 'userId' is added to this array,
	 * which holds the value of `$userId`.
	 * @return boolean whether the operations can be performed by the user.
	 */
Alexander Makarov committed
82
	public function checkAccess($userId, $itemName, $params = [])
83 84 85 86 87 88 89 90
	{
		$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()]].
Alexander Kochetov committed
91
	 * @param mixed $userId the user ID. This should can be either an integer or a string representing
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
	 * the unique identifier of a user. See [[User::id]].
	 * @param string $itemName the name of the operation that need access check
	 * @param array $params name-value pairs that would be passed to biz rules associated
	 * with the tasks and roles assigned to the user. A param with name 'userId' is added to this array,
	 * which holds the value of `$userId`.
	 * @param Assignment[] $assignments the assignments to the specified user
	 * @return boolean whether the operations can be performed by the user.
	 */
	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;
		}
Qiang Xue committed
109
		if ($this->executeBizRule($item->bizRule, $params, $item->data)) {
110 111 112 113 114
			if (in_array($itemName, $this->defaultRoles)) {
				return true;
			}
			if (isset($assignments[$itemName])) {
				$assignment = $assignments[$itemName];
Qiang Xue committed
115
				if ($this->executeBizRule($assignment->bizRule, $params, $assignment->data)) {
116 117 118 119
					return true;
				}
			}
			$query = new Query;
Alexander Makarov committed
120
			$parents = $query->select(['parent'])
121
				->from($this->itemChildTable)
Alexander Makarov committed
122
				->where(['child' => $itemName])
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138
				->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.
	 * @param string $itemName the parent item name
	 * @param string $childName the child item name
	 * @return boolean whether the item is added successfully
139 140
	 * @throws Exception if either parent or child doesn't exist.
	 * @throws InvalidCallException if a loop has been detected.
141 142 143 144 145 146 147 148
	 */
	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)
Luciano Baraglia committed
149
			->where(['or', 'name=:name1', 'name=:name2'], [':name1' => $itemName, ':name2' => $childName])
150 151 152 153 154 155 156 157 158 159 160 161
			->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)) {
162
				throw new InvalidCallException("Cannot add '$childName' as a child of '$itemName'. A loop has been detected.");
163 164
			}
			$this->db->createCommand()
Alexander Makarov committed
165
				->insert($this->itemChildTable, ['parent' => $itemName, 'child' => $childName])
166
				->execute();
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182
			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.
	 * @param string $itemName the parent item name
	 * @param string $childName the child item name
	 * @return boolean whether the removal is successful
	 */
	public function removeItemChild($itemName, $childName)
	{
		return $this->db->createCommand()
Alexander Makarov committed
183
			->delete($this->itemChildTable, ['parent' => $itemName, 'child' => $childName])
184
			->execute() > 0;
185 186 187 188 189 190 191 192 193 194 195
	}

	/**
	 * Returns a value indicating whether a child exists within a parent.
	 * @param string $itemName the parent item name
	 * @param string $childName the child item name
	 * @return boolean whether the child exists
	 */
	public function hasItemChild($itemName, $childName)
	{
		$query = new Query;
Alexander Makarov committed
196
		return $query->select(['parent'])
197
			->from($this->itemChildTable)
Alexander Makarov committed
198
			->where(['parent' => $itemName, 'child' => $childName])
199 200 201 202 203 204 205 206 207 208 209 210 211
			->createCommand($this->db)
			->queryScalar() !== false;
	}

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

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

	/**
	 * Revokes an authorization assignment from a user.
	 * @param mixed $userId the user ID (see [[User::id]])
	 * @param string $itemName the item name
	 * @return boolean whether removal is successful
	 */
	public function revoke($userId, $itemName)
	{
		return $this->db->createCommand()
Alexander Makarov committed
275
			->delete($this->assignmentTable, ['user_id' => $userId, 'item_name' => $itemName])
276
			->execute() > 0;
277 278
	}

279 280 281 282 283 284 285 286 287 288 289 290
	/**
	 * Revokes all authorization assignments from a user.
	 * @param mixed $userId the user ID (see [[User::id]])
	 * @return boolean whether removal is successful
	 */
	public function revokeAll($userId)
	{
		return $this->db->createCommand()
						->delete($this->assignmentTable, ['user_id' => $userId])
						->execute() > 0;
	}

291 292 293 294 295 296
	/**
	 * Returns a value indicating whether the item has been assigned to the user.
	 * @param mixed $userId the user ID (see [[User::id]])
	 * @param string $itemName the item name
	 * @return boolean whether the item has been assigned to the user.
	 */
297
	public function isAssigned($userId, $itemName)
298 299
	{
		$query = new Query;
Alexander Makarov committed
300
		return $query->select(['item_name'])
301
			->from($this->assignmentTable)
Luciano Baraglia committed
302
			->where(['user_id' => $userId, 'item_name' => $itemName])
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317
			->createCommand($this->db)
			->queryScalar() !== false;
	}

	/**
	 * Returns the item assignment information.
	 * @param mixed $userId the user ID (see [[User::id]])
	 * @param string $itemName the item name
	 * @return Assignment the item assignment information. Null is returned if
	 * the item is not assigned to the user.
	 */
	public function getAssignment($userId, $itemName)
	{
		$query = new Query;
		$row = $query->from($this->assignmentTable)
Luciano Baraglia committed
318
			->where(['user_id' => $userId, 'item_name' => $itemName])
319
			->createCommand($this->db)
320
			->queryOne();
321
		if ($row !== false) {
Qiang Xue committed
322
			if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
323 324
				$data = null;
			}
Alexander Makarov committed
325
			return new Assignment([
Qiang Xue committed
326 327 328 329 330
				'manager' => $this,
				'userId' => $row['user_id'],
				'itemName' => $row['item_name'],
				'bizRule' => $row['biz_rule'],
				'data' => $data,
Alexander Makarov committed
331
			]);
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
		} else {
			return null;
		}
	}

	/**
	 * Returns the item assignments for the specified user.
	 * @param mixed $userId the user ID (see [[User::id]])
	 * @return Assignment[] the item assignment information for the user. An empty array will be
	 * returned if there is no item assigned to the user.
	 */
	public function getAssignments($userId)
	{
		$query = new Query;
		$rows = $query->from($this->assignmentTable)
Alexander Makarov committed
347
			->where(['user_id' => $userId])
348 349
			->createCommand($this->db)
			->queryAll();
Alexander Makarov committed
350
		$assignments = [];
351
		foreach ($rows as $row) {
Qiang Xue committed
352
			if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
353 354
				$data = null;
			}
Alexander Makarov committed
355
			$assignments[$row['item_name']] = new Assignment([
Qiang Xue committed
356 357 358 359 360
				'manager' => $this,
				'userId' => $row['user_id'],
				'itemName' => $row['item_name'],
				'bizRule' => $row['biz_rule'],
				'data' => $data,
Alexander Makarov committed
361
			]);
362 363 364 365 366 367 368 369 370 371 372
		}
		return $assignments;
	}

	/**
	 * Saves the changes to an authorization assignment.
	 * @param Assignment $assignment the assignment that has been changed.
	 */
	public function saveAssignment($assignment)
	{
		$this->db->createCommand()
Alexander Makarov committed
373
			->update($this->assignmentTable, [
Qiang Xue committed
374
				'biz_rule' => $assignment->bizRule,
Qiang Xue committed
375
				'data' => $assignment->data === null ? null : serialize($assignment->data),
Alexander Makarov committed
376
			], [
Qiang Xue committed
377 378
				'user_id' => $assignment->userId,
				'item_name' => $assignment->itemName,
Alexander Makarov committed
379
			])
380
			->execute();
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398
	}

	/**
	 * Returns the authorization items of the specific type and user.
	 * @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.
	 */
	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)
Alexander Makarov committed
399
				->where(['type' => $type])
400 401
				->createCommand($this->db);
		} elseif ($type === null) {
Alexander Makarov committed
402 403 404
			$command = $query->select(['name', 'type', 'description', 't1.biz_rule', 't1.data'])
				->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2'])
				->where(['user_id' => $userId, 'name' => new Expression('item_name')])
405 406
				->createCommand($this->db);
		} else {
407
			$command = $query->select(['name', 'type', 'description', 't1.biz_rule', 't1.data'])
Alexander Makarov committed
408 409
				->from([$this->itemTable . ' t1', $this->assignmentTable . ' t2'])
				->where(['user_id' => $userId, 'type' => $type, 'name' => new Expression('item_name')])
410 411
				->createCommand($this->db);
		}
Alexander Makarov committed
412
		$items = [];
413
		foreach ($command->queryAll() as $row) {
Qiang Xue committed
414
			if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
415 416
				$data = null;
			}
Alexander Makarov committed
417
			$items[$row['name']] = new Item([
Qiang Xue committed
418 419 420 421 422 423
				'manager' => $this,
				'name' => $row['name'],
				'type' => $row['type'],
				'description' => $row['description'],
				'bizRule' => $row['biz_rule'],
				'data' => $data,
Alexander Makarov committed
424
			]);
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446
		}
		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.
	 * @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
	 * @param string $bizRule business rule associated with the item. This is a piece of
	 * 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
	 * @throws Exception if an item with the same name already exists
	 */
	public function createItem($name, $type, $description = '', $bizRule = null, $data = null)
	{
		$this->db->createCommand()
Alexander Makarov committed
447
			->insert($this->itemTable, [
448 449 450
				'name' => $name,
				'type' => $type,
				'description' => $description,
Qiang Xue committed
451
				'biz_rule' => $bizRule,
452
				'data' => $data === null ? null : serialize($data),
Alexander Makarov committed
453
			])
454
			->execute();
Alexander Makarov committed
455
		return new Item([
Qiang Xue committed
456 457 458 459 460 461
			'manager' => $this,
			'name' => $name,
			'type' => $type,
			'description' => $description,
			'bizRule' => $bizRule,
			'data' => $data,
Alexander Makarov committed
462
		]);
463 464 465 466 467 468 469 470 471 472 473
	}

	/**
	 * Removes the specified authorization item.
	 * @param string $name the name of the item to be removed
	 * @return boolean whether the item exists in the storage and has been removed
	 */
	public function removeItem($name)
	{
		if ($this->usingSqlite()) {
			$this->db->createCommand()
Alexander Makarov committed
474
				->delete($this->itemChildTable, ['or', 'parent=:name', 'child=:name'], [':name' => $name])
475
				->execute();
476
			$this->db->createCommand()
Alexander Makarov committed
477
				->delete($this->assignmentTable, ['item_name' => $name])
478
				->execute();
479
		}
480
		return $this->db->createCommand()
Alexander Makarov committed
481
			->delete($this->itemTable, ['name' => $name])
482
			->execute() > 0;
483 484 485 486 487 488 489 490 491 492 493
	}

	/**
	 * Returns the authorization item with the specified name.
	 * @param string $name the name of the item
	 * @return Item the authorization item. Null if the item cannot be found.
	 */
	public function getItem($name)
	{
		$query = new Query;
		$row = $query->from($this->itemTable)
Alexander Makarov committed
494
			->where(['name' => $name])
495
			->createCommand($this->db)
496
			->queryOne();
497 498

		if ($row !== false) {
499
			if (!isset($row['data']) || ($data = @unserialize($row['data'])) === false) {
500 501
				$data = null;
			}
Alexander Makarov committed
502
			return new Item([
Qiang Xue committed
503 504 505 506 507 508
				'manager' => $this,
				'name' => $row['name'],
				'type' => $row['type'],
				'description' => $row['description'],
				'bizRule' => $row['biz_rule'],
				'data' => $data,
Alexander Makarov committed
509
			]);
resurtm committed
510
		} else {
511
			return null;
resurtm committed
512
		}
513 514 515 516 517 518 519 520 521 522 523
	}

	/**
	 * Saves an authorization item to persistent storage.
	 * @param Item $item the item to be saved.
	 * @param string $oldName the old item name. If null, it means the item name is not changed.
	 */
	public function saveItem($item, $oldName = null)
	{
		if ($this->usingSqlite() && $oldName !== null && $item->getName() !== $oldName) {
			$this->db->createCommand()
Alexander Makarov committed
524
				->update($this->itemChildTable, ['parent' => $item->getName()], ['parent' => $oldName])
525
				->execute();
526
			$this->db->createCommand()
Alexander Makarov committed
527
				->update($this->itemChildTable, ['child' => $item->getName()], ['child' => $oldName])
528
				->execute();
529
			$this->db->createCommand()
Alexander Makarov committed
530
				->update($this->assignmentTable, ['item_name' => $item->getName()], ['item_name' => $oldName])
531
				->execute();
532 533 534
		}

		$this->db->createCommand()
Alexander Makarov committed
535
			->update($this->itemTable, [
536
				'name' => $item->getName(),
Qiang Xue committed
537 538 539
				'type' => $item->type,
				'description' => $item->description,
				'biz_rule' => $item->bizRule,
Qiang Xue committed
540
				'data' => $item->data === null ? null : serialize($item->data),
Alexander Makarov committed
541
			], [
542
				'name' => $oldName === null ? $item->getName() : $oldName,
Alexander Makarov committed
543
			])
544
			->execute();
545 546 547 548 549 550 551 552 553 554 555 556 557 558 559
	}

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

	/**
	 * Removes all authorization data.
	 */
	public function clearAll()
	{
		$this->clearAssignments();
560 561
		$this->db->createCommand()->delete($this->itemChildTable)->execute();
		$this->db->createCommand()->delete($this->itemTable)->execute();
562 563 564 565 566 567 568
	}

	/**
	 * Removes all authorization assignments.
	 */
	public function clearAssignments()
	{
569
		$this->db->createCommand()->delete($this->assignmentTable)->execute();
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598
	}

	/**
	 * Checks whether there is a loop in the authorization item hierarchy.
	 * @param string $itemName parent item name
	 * @param string $childName the name of the child item that is to be added to the hierarchy
	 * @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;
	}
}