Yii Authentication
admin authentication
In the controllers established by gii, yii’s scaffolding tool, there is a standard method called accessRules() that defines what users can do what actions. A common set is:
public function accessRules()
{
return array(
array('allow', // allow all users to perform 'index' and 'view' actions
'actions'=>array('index','view'),
'users'=>array('*'),
),
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update'),
'users'=>array('@'),
),
array('allow', // allow admin user to perform 'admin' and 'delete' actions
'actions'=>array('admin','delete'),
'users'=>array('admin'),
),
array('deny', // deny all users
'users'=>array('*'),
),
);
}
The comments explain what each array means. An interesting question, however, is how you get a user to count as an ‘admin’? Is there some method or class somewhere that store this information? And if so, how do I get in it?
If you create new users you might devote considerable amount of time trying to get them into the admin class, all to no avail. As far as I can tell, the ‘admin’ refers to usernames rather than a class of user. So if your username is ‘admin’ you can do the restricted actions. If it isn’t, you can’t.
There are a couple of choices here. One is to keep a user whose name is ‘admin’: this has the virtue of simplicity and, since yii will always generate this condition everytime you generate a new site, it also means you’ll not have to go changing ever constructor in your new site as well.
The other choices are to change the code, either to allow some other determinant there. One approach, modified very slightly from an example in Larry Ullman’s blog, is to change ‘admin’ to the wildcard '<nowiki>
‘@ (=logged in users) and then add an expression for some other condition:
array('allow',
'actions'=>array('admin','delete'),
'users'=>array('@'),
'expression'=>'isset($user->role) && ($user->role==="editor")'
),
You could even just hardwire somebody’s name in or some other attribute:
bc.. array('allow',
'actions'=>array('admin','delete'),
'users'=>array('@'),
'expression'=>'isset($user->email) && ($user->role==="admin@example.com")'
),
For more discussion, see
- http://www.larryullman.com/2010/01/14/yii-framework-access-control-lists/
- http://www.larryullman.com/2010/01/04/simple-authentication-with-the-yii-framework/
- http://www.larryullman.com/search/authorization
Commenting is closed for this article.