3
* CDbAuthManager class file.
5
* @author Qiang Xue <qiang.xue@gmail.com>
6
* @link http://www.yiiframework.com/
7
* @copyright Copyright © 2008-2011 Yii Software LLC
8
* @license http://www.yiiframework.com/license/
12
* CDbAuthManager represents an authorization manager that stores authorization information in database.
14
* The database connection is specified by {@link connectionID}. And the database schema
15
* should be as described in "framework/web/auth/schema.sql". You may change the names of
16
* the three tables used to store the authorization data by setting {@link itemTable},
17
* {@link itemChildTable} and {@link assignmentTable}.
19
* @author Qiang Xue <qiang.xue@gmail.com>
20
* @version $Id: CDbAuthManager.php 2799 2011-01-01 19:31:13Z qiang.xue $
21
* @package system.web.auth
24
class CDbAuthManager extends CAuthManager
27
* @var string the ID of the {@link CDbConnection} application component. Defaults to 'db'.
28
* The database must have the tables as declared in "framework/web/auth/schema.sql".
30
public $connectionID='db';
32
* @var string the name of the table storing authorization items. Defaults to 'AuthItem'.
34
public $itemTable='AuthItem';
36
* @var string the name of the table storing authorization item hierarchy. Defaults to 'AuthItemChild'.
38
public $itemChildTable='AuthItemChild';
40
* @var string the name of the table storing authorization item assignments. Defaults to 'AuthAssignment'.
42
public $assignmentTable='AuthAssignment';
44
* @var CDbConnection the database connection. By default, this is initialized
45
* automatically as the application component whose ID is indicated as {@link connectionID}.
49
private $_usingSqlite;
52
* Initializes the application component.
53
* This method overrides the parent implementation by establishing the database connection.
55
public function init()
59
$this->getDbConnection()->setActive(true);
60
$this->_usingSqlite=!strncmp($this->getDbConnection()->getDriverName(),'sqlite',6);
64
* Performs access check for the specified user.
65
* @param string $itemName the name of the operation that need access check
66
* @param mixed $userId the user ID. This should can be either an integer and a string representing
67
* the unique identifier of a user. See {@link IWebUser::getId}.
68
* @param array $params name-value pairs that would be passed to biz rules associated
69
* with the tasks and roles assigned to the user.
70
* @return boolean whether the operations can be performed by the user.
72
public function checkAccess($itemName,$userId,$params=array())
74
$assignments=$this->getAuthAssignments($userId);
75
return $this->checkAccessRecursive($itemName,$userId,$params,$assignments);
79
* Performs access check for the specified user.
80
* This method is internally called by {@link checkAccess}.
81
* @param string $itemName the name of the operation that need access check
82
* @param mixed $userId the user ID. This should can be either an integer and a string representing
83
* the unique identifier of a user. See {@link IWebUser::getId}.
84
* @param array $params name-value pairs that would be passed to biz rules associated
85
* with the tasks and roles assigned to the user.
86
* @param array $assignments the assignments to the specified user
87
* @return boolean whether the operations can be performed by the user.
90
protected function checkAccessRecursive($itemName,$userId,$params,$assignments)
92
if(($item=$this->getAuthItem($itemName))===null)
94
Yii::trace('Checking permission "'.$item->getName().'"','system.web.auth.CDbAuthManager');
95
if($this->executeBizRule($item->getBizRule(),$params,$item->getData()))
97
if(in_array($itemName,$this->defaultRoles))
99
if(isset($assignments[$itemName]))
101
$assignment=$assignments[$itemName];
102
if($this->executeBizRule($assignment->getBizRule(),$params,$assignment->getData()))
105
$sql="SELECT parent FROM {$this->itemChildTable} WHERE child=:name";
106
foreach($this->db->createCommand($sql)->bindValue(':name',$itemName)->queryColumn() as $parent)
108
if($this->checkAccessRecursive($parent,$userId,$params,$assignments))
116
* Adds an item as a child of another item.
117
* @param string $itemName the parent item name
118
* @param string $childName the child item name
119
* @throws CException if either parent or child doesn't exist or if a loop has been detected.
121
public function addItemChild($itemName,$childName)
123
if($itemName===$childName)
124
throw new CException(Yii::t('yii','Cannot add "{name}" as a child of itself.',
125
array('{name}'=>$itemName)));
126
$sql="SELECT * FROM {$this->itemTable} WHERE name=:name1 OR name=:name2";
127
$command=$this->db->createCommand($sql);
128
$command->bindValue(':name1',$itemName);
129
$command->bindValue(':name2',$childName);
130
$rows=$command->queryAll();
133
if($rows[0]['name']===$itemName)
135
$parentType=$rows[0]['type'];
136
$childType=$rows[1]['type'];
140
$childType=$rows[0]['type'];
141
$parentType=$rows[1]['type'];
143
$this->checkItemChildType($parentType,$childType);
144
if($this->detectLoop($itemName,$childName))
145
throw new CException(Yii::t('yii','Cannot add "{child}" as a child of "{name}". A loop has been detected.',
146
array('{child}'=>$childName,'{name}'=>$itemName)));
148
$sql="INSERT INTO {$this->itemChildTable} (parent,child) VALUES (:parent,:child)";
149
$command=$this->db->createCommand($sql);
150
$command->bindValue(':parent',$itemName);
151
$command->bindValue(':child',$childName);
155
throw new CException(Yii::t('yii','Either "{parent}" or "{child}" does not exist.',array('{child}'=>$childName,'{parent}'=>$itemName)));
159
* Removes a child from its parent.
160
* Note, the child item is not deleted. Only the parent-child relationship is removed.
161
* @param string $itemName the parent item name
162
* @param string $childName the child item name
163
* @return boolean whether the removal is successful
165
public function removeItemChild($itemName,$childName)
167
$sql="DELETE FROM {$this->itemChildTable} WHERE parent=:parent AND child=:child";
168
$command=$this->db->createCommand($sql);
169
$command->bindValue(':parent',$itemName);
170
$command->bindValue(':child',$childName);
171
return $command->execute()>0;
175
* Returns a value indicating whether a child exists within a parent.
176
* @param string $itemName the parent item name
177
* @param string $childName the child item name
178
* @return boolean whether the child exists
180
public function hasItemChild($itemName,$childName)
182
$sql="SELECT parent FROM {$this->itemChildTable} WHERE parent=:parent AND child=:child";
183
$command=$this->db->createCommand($sql);
184
$command->bindValue(':parent',$itemName);
185
$command->bindValue(':child',$childName);
186
return $command->queryScalar()!==false;
190
* Returns the children of the specified item.
191
* @param mixed $names the parent item name. This can be either a string or an array.
192
* The latter represents a list of item names (available since version 1.0.5).
193
* @return array all child items of the parent
195
public function getItemChildren($names)
197
if(is_string($names))
198
$condition='parent='.$this->db->quoteValue($names);
199
else if(is_array($names) && $names!==array())
201
foreach($names as &$name)
202
$name=$this->db->quoteValue($name);
203
$condition='parent IN ('.implode(', ',$names).')';
205
$sql="SELECT name, type, description, bizrule, data FROM {$this->itemTable}, {$this->itemChildTable} WHERE $condition AND name=child";
207
foreach($this->db->createCommand($sql)->queryAll() as $row)
209
if(($data=@unserialize($row['data']))===false)
211
$children[$row['name']]=new CAuthItem($this,$row['name'],$row['type'],$row['description'],$row['bizrule'],$data);
217
* Assigns an authorization item to a user.
218
* @param string $itemName the item name
219
* @param mixed $userId the user ID (see {@link IWebUser::getId})
220
* @param string $bizRule the business rule to be executed when {@link checkAccess} is called
221
* for this particular authorization item.
222
* @param mixed $data additional data associated with this assignment
223
* @return CAuthAssignment the authorization assignment information.
224
* @throws CException if the item does not exist or if the item has already been assigned to the user
226
public function assign($itemName,$userId,$bizRule=null,$data=null)
228
if($this->usingSqlite() && $this->getAuthItem($itemName)===null)
229
throw new CException(Yii::t('yii','The item "{name}" does not exist.',array('{name}'=>$itemName)));
231
$sql="INSERT INTO {$this->assignmentTable} (itemname,userid,bizrule,data) VALUES (:itemname,:userid,:bizrule,:data)";
232
$command=$this->db->createCommand($sql);
233
$command->bindValue(':itemname',$itemName);
234
$command->bindValue(':userid',$userId);
235
$command->bindValue(':bizrule',$bizRule);
236
$command->bindValue(':data',serialize($data));
238
return new CAuthAssignment($this,$itemName,$userId,$bizRule,$data);
242
* Revokes an authorization assignment from a user.
243
* @param string $itemName the item name
244
* @param mixed $userId the user ID (see {@link IWebUser::getId})
245
* @return boolean whether removal is successful
247
public function revoke($itemName,$userId)
249
$sql="DELETE FROM {$this->assignmentTable} WHERE itemname=:itemname AND userid=:userid";
250
$command=$this->db->createCommand($sql);
251
$command->bindValue(':itemname',$itemName);
252
$command->bindValue(':userid',$userId);
253
return $command->execute()>0;
257
* Returns a value indicating whether the item has been assigned to the user.
258
* @param string $itemName the item name
259
* @param mixed $userId the user ID (see {@link IWebUser::getId})
260
* @return boolean whether the item has been assigned to the user.
262
public function isAssigned($itemName,$userId)
264
$sql="SELECT itemname FROM {$this->assignmentTable} WHERE itemname=:itemname AND userid=:userid";
265
$command=$this->db->createCommand($sql);
266
$command->bindValue(':itemname',$itemName);
267
$command->bindValue(':userid',$userId);
268
return $command->queryScalar()!==false;
272
* Returns the item assignment information.
273
* @param string $itemName the item name
274
* @param mixed $userId the user ID (see {@link IWebUser::getId})
275
* @return CAuthAssignment the item assignment information. Null is returned if
276
* the item is not assigned to the user.
278
public function getAuthAssignment($itemName,$userId)
280
$sql="SELECT * FROM {$this->assignmentTable} WHERE itemname=:itemname AND userid=:userid";
281
$command=$this->db->createCommand($sql);
282
$command->bindValue(':itemname',$itemName);
283
$command->bindValue(':userid',$userId);
284
if(($row=$command->queryRow($sql))!==false)
286
if(($data=@unserialize($row['data']))===false)
288
return new CAuthAssignment($this,$row['itemname'],$row['userid'],$row['bizrule'],$data);
295
* Returns the item assignments for the specified user.
296
* @param mixed $userId the user ID (see {@link IWebUser::getId})
297
* @return array the item assignment information for the user. An empty array will be
298
* returned if there is no item assigned to the user.
300
public function getAuthAssignments($userId)
302
$sql="SELECT * FROM {$this->assignmentTable} WHERE userid=:userid";
303
$command=$this->db->createCommand($sql);
304
$command->bindValue(':userid',$userId);
305
$assignments=array();
306
foreach($command->queryAll($sql) as $row)
308
if(($data=@unserialize($row['data']))===false)
310
$assignments[$row['itemname']]=new CAuthAssignment($this,$row['itemname'],$row['userid'],$row['bizrule'],$data);
316
* Saves the changes to an authorization assignment.
317
* @param CAuthAssignment $assignment the assignment that has been changed.
319
public function saveAuthAssignment($assignment)
321
$sql="UPDATE {$this->assignmentTable} SET bizrule=:bizrule, data=:data WHERE itemname=:itemname AND userid=:userid";
322
$command=$this->db->createCommand($sql);
323
$command->bindValue(':bizrule',$assignment->getBizRule());
324
$command->bindValue(':data',serialize($assignment->getData()));
325
$command->bindValue(':itemname',$assignment->getItemName());
326
$command->bindValue(':userid',$assignment->getUserId());
331
* Returns the authorization items of the specific type and user.
332
* @param integer $type the item type (0: operation, 1: task, 2: role). Defaults to null,
333
* meaning returning all items regardless of their type.
334
* @param mixed $userId the user ID. Defaults to null, meaning returning all items even if
335
* they are not assigned to a user.
336
* @return array the authorization items of the specific type.
338
public function getAuthItems($type=null,$userId=null)
340
if($type===null && $userId===null)
342
$sql="SELECT * FROM {$this->itemTable}";
343
$command=$this->db->createCommand($sql);
345
else if($userId===null)
347
$sql="SELECT * FROM {$this->itemTable} WHERE type=:type";
348
$command=$this->db->createCommand($sql);
349
$command->bindValue(':type',$type);
351
else if($type===null)
353
$sql="SELECT name,type,description,t1.bizrule,t1.data
354
FROM {$this->itemTable} t1, {$this->assignmentTable} t2
355
WHERE name=itemname AND userid=:userid";
356
$command=$this->db->createCommand($sql);
357
$command->bindValue(':userid',$userId);
361
$sql="SELECT name,type,description,t1.bizrule,t1.data
362
FROM {$this->itemTable} t1, {$this->assignmentTable} t2
363
WHERE name=itemname AND type=:type AND userid=:userid";
364
$command=$this->db->createCommand($sql);
365
$command->bindValue(':type',$type);
366
$command->bindValue(':userid',$userId);
369
foreach($command->queryAll() as $row)
371
if(($data=@unserialize($row['data']))===false)
373
$items[$row['name']]=new CAuthItem($this,$row['name'],$row['type'],$row['description'],$row['bizrule'],$data);
379
* Creates an authorization item.
380
* An authorization item represents an action permission (e.g. creating a post).
381
* It has three types: operation, task and role.
382
* Authorization items form a hierarchy. Higher level items inheirt permissions representing
383
* by lower level items.
384
* @param string $name the item name. This must be a unique identifier.
385
* @param integer $type the item type (0: operation, 1: task, 2: role).
386
* @param string $description description of the item
387
* @param string $bizRule business rule associated with the item. This is a piece of
388
* PHP code that will be executed when {@link checkAccess} is called for the item.
389
* @param mixed $data additional data associated with the item.
390
* @return CAuthItem the authorization item
391
* @throws CException if an item with the same name already exists
393
public function createAuthItem($name,$type,$description='',$bizRule=null,$data=null)
395
$sql="INSERT INTO {$this->itemTable} (name,type,description,bizrule,data) VALUES (:name,:type,:description,:bizrule,:data)";
396
$command=$this->db->createCommand($sql);
397
$command->bindValue(':type',$type);
398
$command->bindValue(':name',$name);
399
$command->bindValue(':description',$description);
400
$command->bindValue(':bizrule',$bizRule);
401
$command->bindValue(':data',serialize($data));
403
return new CAuthItem($this,$name,$type,$description,$bizRule,$data);
407
* Removes the specified authorization item.
408
* @param string $name the name of the item to be removed
409
* @return boolean whether the item exists in the storage and has been removed
411
public function removeAuthItem($name)
413
if($this->usingSqlite())
415
$sql="DELETE FROM {$this->itemChildTable} WHERE parent=:name1 OR child=:name2";
416
$command=$this->db->createCommand($sql);
417
$command->bindValue(':name1',$name);
418
$command->bindValue(':name2',$name);
421
$sql="DELETE FROM {$this->assignmentTable} WHERE itemname=:name";
422
$command=$this->db->createCommand($sql);
423
$command->bindValue(':name',$name);
427
$sql="DELETE FROM {$this->itemTable} WHERE name=:name";
428
$command=$this->db->createCommand($sql);
429
$command->bindValue(':name',$name);
431
return $command->execute()>0;
435
* Returns the authorization item with the specified name.
436
* @param string $name the name of the item
437
* @return CAuthItem the authorization item. Null if the item cannot be found.
439
public function getAuthItem($name)
441
$sql="SELECT * FROM {$this->itemTable} WHERE name=:name";
442
$command=$this->db->createCommand($sql);
443
$command->bindValue(':name',$name);
444
if(($row=$command->queryRow())!==false)
446
if(($data=@unserialize($row['data']))===false)
448
return new CAuthItem($this,$row['name'],$row['type'],$row['description'],$row['bizrule'],$data);
455
* Saves an authorization item to persistent storage.
456
* @param CAuthItem $item the item to be saved.
457
* @param string $oldName the old item name. If null, it means the item name is not changed.
459
public function saveAuthItem($item,$oldName=null)
461
if($this->usingSqlite() && $oldName!==null && $item->getName()!==$oldName)
463
$sql="UPDATE {$this->itemChildTable} SET parent=:newName WHERE parent=:name";
464
$command=$this->db->createCommand($sql);
465
$command->bindValue(':name',$oldName);
466
$command->bindValue(':newName',$item->getName());
468
$sql="UPDATE {$this->itemChildTable} SET child=:newName WHERE child=:name";
469
$command=$this->db->createCommand($sql);
470
$command->bindValue(':name',$oldName);
471
$command->bindValue(':newName',$item->getName());
473
$sql="UPDATE {$this->assignmentTable} SET itemname=:newName WHERE itemname=:name";
474
$command=$this->db->createCommand($sql);
475
$command->bindValue(':name',$oldName);
476
$command->bindValue(':newName',$item->getName());
480
$sql="UPDATE {$this->itemTable} SET name=:newName, type=:type, description=:description, bizrule=:bizrule, data=:data WHERE name=:name";
481
$command=$this->db->createCommand($sql);
482
$command->bindValue(':type',$item->getType());
483
$command->bindValue(':name',$oldName===null?$item->getName():$oldName);
484
$command->bindValue(':newName',$item->getName());
485
$command->bindValue(':description',$item->getDescription());
486
$command->bindValue(':bizrule',$item->getBizRule());
487
$command->bindValue(':data',serialize($item->getData()));
492
* Saves the authorization data to persistent storage.
494
public function save()
499
* Removes all authorization data.
501
public function clearAll()
503
$this->clearAuthAssignments();
504
$this->db->createCommand("DELETE FROM {$this->itemChildTable}")->execute();
505
$this->db->createCommand("DELETE FROM {$this->itemTable}")->execute();
509
* Removes all authorization assignments.
511
public function clearAuthAssignments()
513
$this->db->createCommand("DELETE FROM {$this->assignmentTable}")->execute();
517
* Checks whether there is a loop in the authorization item hierarchy.
518
* @param string $itemName parent item name
519
* @param string $childName the name of the child item that is to be added to the hierarchy
520
* @return boolean whether a loop exists
522
protected function detectLoop($itemName,$childName)
524
if($childName===$itemName)
526
foreach($this->getItemChildren($childName) as $child)
528
if($this->detectLoop($itemName,$child->getName()))
535
* @return CDbConnection the DB connection instance
536
* @throws CException if {@link connectionID} does not point to a valid application component.
538
protected function getDbConnection()
542
else if(($this->db=Yii::app()->getComponent($this->connectionID)) instanceof CDbConnection)
545
throw new CException(Yii::t('yii','CDbAuthManager.connectionID "{id}" is invalid. Please make sure it refers to the ID of a CDbConnection application component.',
546
array('{id}'=>$this->connectionID)));
550
* @return boolean whether the database is a SQLite database
552
protected function usingSqlite()
554
return $this->_usingSqlite;