Installing Yii Users and Rights in 5 Steps

So you've got your clean Yii installation*...now what? Frequently the next step is adding support for users and some sort of permissioning schema. The official Yii guide to Authentication and Authorization is a very comprehensive and important piece of documentation — please do take the hour or so necessary to read it and try to understand it. You could skip it, of course, and just use the following steps to get your app working, but you'd really be missing out, especially if you're new to Yii, new to object-oriented PHP, or just new to authentication/authorization methodologies.

Anyone could roll his own user and permissioning framework, but luckily there are two well-supported Yii extensions for this: yii-user and rights. Both come with installation instructions, but I'm writing it all out in steps for easy reference.

By the way, I've created a github repository with a working version of my installation. You can grab it here, or just clone it:

git clone git@github.com:benjaminlhaas/Yii-with-Users-and-Rights.git

If you use this, you'll need to run the two migration scripts in the webapp/protected/migrations directory and probably change some directory permissions. Check out the README in the root.

If you still want to install yii-users and rights step-by-step, here are the instructions:


Step 1. Download the yii-user and rights extensions and unzip them.

Step 2. Move the extensions to your webapp's modules directory (you may have to create this directory under webapp/protected). For my application, which I'm calling test, the extensions live in these locations:

  • /webapp/protected/modules/user
  • /webapp/protected/modules/rights


Step 3. This step is optional. Open the yii-user mysql schema (located at /webapp/protected/modules/user/data/schema.mysql.sql) in a text editor and remove the 'tbl_' prefix from all the table names. Personally, I prefer not to use this naming convention for my database tables.

Step 3.1. This step is not optional! As of User module build 0.3-61-gfc69518, there is an error in the mysql schema referenced in step 3 above. Inside the definition of the 'users' table, you'll need to change the column "lastvisit" to "lastvisit_at" to match the module code. If this schema gets fixed in a future build, I will remove this step.

Step 4. Configure the Yii application. Open /webapp/protected/config/main.php in a text editor for editing.

Update the 'import' section with the extension references as such:

'import'=>array(
        ...
        'application.modules.user.models.*',
        'application.modules.user.components.*',
        'application.modules.rights.*',
        'application.modules.rights.components.*',
        ...
),

Next, update the 'modules' section with the extension references as such:

'modules'=>array(
        ...
        'user'=>array(
                'tableUsers' => 'users',
                'tableProfiles' => 'profiles',
                'tableProfileFields' => 'profiles_fields',
        ),
        'rights'=>array(
                'install'=>true,
        ),
        ...
),

Two things of note. First, you only need to add the 'tableUsers', 'tableProfiles', and 'tableProfileFields' lines if you peformed step 3. Second, notice that 'install' is set to true for the rights extension. We'll need to change it to false later after we've finished the installation.

Next, update the 'components' section as such:

'components'=>array(
        ...
        'user'=>array(
                'class'=>'RWebUser',
                // enable cookie-based authentication
                'allowAutoLogin'=>true,
                'loginUrl'=>array('/user/login'),
        ),
        'authManager'=>array(
                'class'=>'RDbAuthManager',
                'connectionID'=>'db',
                'defaultRoles'=>array('Authenticated', 'Guest'),
        ),
        ...
),


Step 5. Finally, install the yii-user and rights database schemas. The yii-user extension requires that you do this manually, but the rights extension provides an installer.

For yii-user, import the yii-user MySQL database schema (same one referenced in step 3; this schema is located at /webapp/protected/modules/user/data/schema.mysql.sql). I executed this MySQL command:
source ~/Sites/yii/test/webapp/protected/modules/user/data/schema.mysql.sql;

For rights, navigate to test.local/rights to install. Click "yes" if you're prompted to do so.

If everything went smoothly, you're all set! You should be able to log in with u/p = admin/admin or u/p = demo/demo and check out these extensions. Couple things you can do to clean up now. In your main config file, change 'install' to false (or comment out the line) in the 'modules'->'rights' section. Additionally, you can update your primary navigation bar in your main page template to provide easy access to these new extensions. I made the following changes to the CMenu widget in the "mainmenu" div in /webapp/protected/views/layouts/main.php:

'items'=>array(
        ...
        /* array('label'=>'Login', 'url'=>array('/site/login'), 'visible'=>Yii::app()->user->isGuest), */
        /* array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/site/logout'), 'visible'=>!Yii::app()->user->isGuest), */
        array('label'=>'Rights', 'url'=>array('/rights'), 'visible'=>!Yii::app()->user->isGuest),
        array('url'=>Yii::app()->getModule('user')->loginUrl, 'label'=>Yii::app()->getModule('user')->t("Login"), 'visible'=>Yii::app()->user->isGuest),
        array('url'=>Yii::app()->getModule('user')->registrationUrl, 'label'=>Yii::app()->getModule('user')->t("Register"), 'visible'=>Yii::app()->user->isGuest),
        array('url'=>Yii::app()->getModule('user')->profileUrl, 'label'=>Yii::app()->getModule('user')->t("Profile"), 'visible'=>!Yii::app()->user->isGuest),
        array('url'=>Yii::app()->getModule('user')->logoutUrl, 'label'=>Yii::app()->getModule('user')->t("Logout").' ('.Yii::app()->user->name.')', 'visible'=>!Yii::app()->user->isGuest),
        ...
),

Please let me know of any corrections or suggestions in the comments area below.

*What? You don't have a clean Yii installation? See this tutorial for help with this step. Hurry back!

Category:
Tags:

Comments

Yii application

Nice tutorial. Happy to see someone publishing quality content on Yii. We have been working on a new open source CRM application that is written in PHP utilizing JQuery, Yii, and RedBeanPHP and relies heavily on test driven development. It might be one of the most complex projects on Yii to date.

Right now, we have 1000+ unit tests running across eight server configurations. We utilize selenium as well for a nice set of functional tests too. It would be incredibly helpful to get your technical feedback and recommendations so that we can improve the application. Take a look and let me know what you think: http://zurmo.org

Re: Yii application

Hi Ray, thanks for stopping by. Funny, we were just talking in the office on Friday about CRM/CMS systems built in Yii, so your timing is perfect. Zurmo looks pretty awesome — I'll definitely check it out and give the heads up to my co-workers as well.

It's great to see it in just

It's great to see it in just 5 steps! You have made it much much easier! Thanks!

running the rights installer

Hey man... I have been messing with this since yesterday evening, I got the config file updated, the extensions in a modules folder, ran the sql statement for yii-user on my database, and configured the database in the config file.

You say go to test.local/rights to run the installer for rights.

My project is simply called "rights" and I access it by going to localhost/rights, what url do I need to go to in order to install? Or is it a console command?

I have tried localhost/rights/index.php?r=rights to no avail.

Any advice would be greatly appreciated.

Also, in your 'import' array you have:
'application.modules.right.*',

and I think it is supposed to be
'application.modules.rights.*',

Thanks for taking the time to write this article.

thanks!

I was just about to start looking into this, and then I saw your reply below. Thanks so much for trying this out and giving some feedback, I really appreciate it. I also made the small fix you pointed out. Feel free to get in touch if you have any more questions or comments.

Installing Yii Rights Command

I am using wamp, and if the moderator of this board doesn't mind I would like to post my solution to the installation URL so that it might help someone else.

Once you have followed the steps above, where the author says go to:
test.local/rights

If you are using Wamp you should navigate to:
path/to/your/application/index.php?r=rights/install

This should start the installer that I scoured the internet trying to find out how to launch.

Hope this helps someone, and to the author of this page, your article helped me tremendously and I really appresciate it.

thanks

Thanks alot - your answer soveld all my problems after several days struggling

RIghts installed and not working.

Hi guys, i had installed the yii rights module and configured it, but the functionality is not working, how to make it functionally working.

more info?

Hi, I'm happy to try to help. What exactly isn't working?

The roles , the tasks and the

The roles , the tasks and the operations are not assigned to the user, it is default showing all the things. Example rights was shown to all the users.

In the Zii widget menu, i had given the coding like this for the rights:

array('label'=>'Rights','url'=>array('/rights'), 'visible'=>Yii::app()->user->checkAccess(Rights::module()->superuserName)),

some suggestions

Off the top of my head, here are some thoughts to consider:

- On the Operations page, make sure you have created some Operations that can be checked for access. For example, create an Operation called "View Rights Nav Item."

- On the Roles page, make sure you have created a role (other than Superuser). For example, create a role called "Editor."

- On the Permissions page, make sure you have can assign/revoke permission to the "View Rights Nav Item" Operation for the Editor role.

- Make sure you have a user with the Editor role assignment.

- When calling Yii::app()->user->checkAccess(), try passing in the name of an Operation. For example, call Yii::app()->user->checkAccess('View Rights Nav Item').

- The Superuser can see everything, so log in as this new Editor user in a different browser. Then, in your original browser, try assigning and revoking "View Rights Nav Item" permissions and see if the nav bar changes for the Editor user.

Hi, Thanks dude, I had done

Hi, Thanks dude,
I had done the things as you specified in the above manner and the menu is showing as per the settings which i had made.

Another one question,

How can i control the users in the controller.
Showing some options to the authenticated users only and showing some options to the admin users only..

Hi Ben, As you said, i had

Hi Ben,

As you said, i had changed the things for the menu and it is working fine.

How to restrict the user while viewing the controllers.

Below was the example:

public function filters()
{
return array(
'rights',
);
}

public function allowedActions()
{
return 'index';
}

Need an operation for your controller operation

Hi Srinivasan,

If you have implemented the controler filters method as you wrote above, you shouldn't have to do any more work in your controller code. You do, however, have to create the Rights operations that correspond to each of your controller's actions.

For example, to apply the Rights filter to actionIndex inside the Site controller, you need to create an operation called "Site.Index." You can do this manually by navigating to the Operations tab (/rights/authItem/operations) and creating a new operation called "Site.Index." Alternately, you can click on the "Generate items for controller actions" on the Permissions tab (/rights/authItem/permissions), check off the controller actions for which you wish to create operations, and click "Generate."

Once you have the operation for your controller action, you can apply permissions as usual on the Permissions tab.

Hope that helps.

There must be at least one superuser!

Hi Ben

I can't make it work. This is the error:

Error 403
There must be at least one superuser!

What could it be?

Thanks

migration script

Hi there, did you run the migration scripts? Script m111222_183233_create_user_tables.php creates a superuser.

hello have tried to install

hello
have tried to install but gets this error when using rights
Error 403

There must be at least one superuser!

and how do you run the migration script?

thanks Martin

There must be at least one superuser!

I encountered this same error. For me it turned out that I need to create a 'User' model. This I did by:

1) Activating Gii by uncommenting it out in the webapp/protected/config/main.php file
2) Going to http://localhost/relational/index.php?r=gii
3) Clicking on Model Generator, filling it out with the relevant information (Table Name = 'users', Model Name = 'Users')
4) Then I visited webapp/index.php?r=rights/install

... and it worked!

Hope that helps

there's a line in the source

there's a line in the source code that you have to comment out. check in the yii rights official extension page....

it's a little bug but there's a little hack that removes it and everything starts working

Hi, can you elaborate on

Hi, can you elaborate on this? I looked on the extension page for Yii Rights and can't find anything saying to comment out a line.

rights' little hack

there's a section (right at the bottom) of my post that explains the little hack you have to make in order to make rights work:

http://queirozf.com/reminders/installing-yii-rights-extension

That works if you're rolling

That works if you're rolling your own User framework, but this blog post is specifically about installing the Rights module along with the User module, so I personally don't recommend the hack that you suggest.

There's better (more elegant)

There's better (more elegant) solution:

In file ../modules/rights/components/RAuthorizer.php Line: 304

use Yii::app()->getModule('user')->isAdmin() ) to test admin session:

CODE:
if( !Yii::app()->getModule('user')->isAdmin() )
throw new CHttpException(403, Rights::t('core', 'There must be at least one superuser!'));

Hi, i had the same problem,

Hi, i had the same problem, but googling i found this page http://translate.google.com/translate?sl=auto&tl=en&js=n&prev=_t&hl=en&i... (i think is russian, thank to google translate), the problem was that i did not set roles to Admin & Demo User in AuthItem & AuthAssignment

Bye

superuser error fix

Hy!

Error 403
There must be at least one superuser!

How to fix...

main.php
'modules'=>array(
...
'rights'=>array(
'install'=>true, // Whether to enable installer.
'superuserName'=>'Admin', //superuser name!!
....

good luck! :)

see above

Did you read the other comments above? Did you try out the suggestions?

hi, i'm trying to install the

hi, i'm trying to install the bootstrap Extension and i'm truggling for 4 days please help me i have always the same erreur "PHP warning

include(EBootstrapActiveForm.php) [function.include]: failed to open stream: No such file or directory "

Yii Bootstrap

Sorry, I'm not familiar with this extension. I suggest getting in touch with the authors here: http://visualappeal.github.com/YiiBootstrap/.

there are 2 different

there are 2 different yii-bootstrap extensions. one made by cniska www.cniska.net/yii-bootstrap/ and another one too visualappeal.github.com/YiiBootstrap/

they are two different extensions made by two different people....

i personally use cniskas, but both are ok I think

Excellent explanation,

Excellent explanation, straight to the point. For some reason, I was missing some steps in the installation of Rights (like the ConnectionID parameter!). I have both User and Rights working now.

Thanks!

Excellent explanation,

Sir, i follow your step by step instruction and my application run smooth, i just want to ask you i want my index.php to be my login? how can i redirect to user/login when i type to my browser example localhost/blog/index.php but in index view should be my user/login.

Couple options

The first option is to simply redirect the user to the login page in the actionIndex() action in your Blog controller. Example:

public function actionIndex()
{
        if (Yii::app()->user->isGuest)
        {
                $this->redirect('/user/login'); // Redirect anonymous users to the login page
        }
        else
        {
                $this->render('index');
        }
}

The other option, which is role based, is to use rights operations and permissions (though admittedly I haven't tried it for this purpose). You need to first create a Rights operation for the index page, and then grant a permission to that operation for authenticated users. Once you have everything installed and working properly, do the following:

1. Add the operation: navigate to /rights/authItem/operations and add an Operation called Blog.Index.
2. Add the permission: navigate to /rights/authItem/permissions and assign access to the operation Blog.Index to Authenticated users.

Hope this helps.

Thank You so much for the

Thank You so much for the help sir, by the way sir i have a problem again because i follow the yii blog tutorial and i run it.. when i installed rights ok.. but when i installed the yii user extension when i login to user/login, there is no layout.. hope you can help sir, but when i copy my protected/views/layout/main.php to protected/modules/user/views/layout the layout appeared again.. how is that sir? is there i something i put code when i follow the blog tutorial, because i installed the yii user extension as you post..

sorry

I wish I could help you but this is just too confusing for me. I'm not sure why you copied the template from your views directory to the module. Perhaps someone else reading this can help.

Thanks for Biz rule for

Thanks for Biz rule for authenticated users ;)

how to get search option

I want to serach like grid-view of admin page,how I can achiece it.

Great, Work for me. But

Great, Work for me. But Yii-user must be installed first. When I test both i have many errors.

Are these modules working together in 1.11?

I followed these instructions and user and rights in an attempt to get this installed under the latest framework 1.11. Does anyone have both of these modules working together in harmony for 1.11? As a reference and sanity check I cloned the 1.8 version above (thank you) but there are large inconsistencies. For example console.php is empty (no declarations) in the 1.8 above but following the instructions for the latest of both modules and 1.11 has a populated modules and components section in config/console.php

Also users looks for
'user'=>array(
// enable cookie-based authentication
'class' => 'WebUser',
), in config/main.php
and rights looks for
'user'=>array(
// enable cookie-based authentication
'class' => 'RWebUser',
),

I get errors (in yii 1.11 on the profile page: The table "users" for active record class "User" cannot be found in the database. ) everywhere for all combos of one, the other or both (Webuser. RWebuser) unfortunately. So close yet so far

Thanks for a great guide btw! Its been helpful tho it seems it's geared toward older yii only.

I'm seeing this also with

I'm seeing this also with both 1.11 and 1.12. I've modified the config/main.php to user WebUser instead of RWebUser and I can get the user module to work properly. One minor point on that though, is the modules/user/data/schema.mysql.sql is incorrect with lastvisit field in the user table. The code references lastvisit_at everywhere so if you plan to run the mysql sql for the data setup, you might want to modify that first. It also prefixes tbl_ to all the tables, so if you do not have that as your default, you should update it as well.

Back to WebUser versus RWebUser, so I now have the user module 'working', i.e. I can go to index.php?r=user and all its actions. If I try to set up the rights module (install => true), I hit index.php?r=rights and got an exception with superuser not being a field of WebUser.

Ok here's the real screwy thing for me now. I started typing my findings here to help me figure out the inherited user class issues and index.php?r=rights now works. It pointed me to 'are you sure you want to reinstall?'. I've set install=>false now and the ui/functionality come up correctly. The ONLY thing I think I did in the meantime was modify modules/rights/components/RInstaller.php and change references from RWebUser to WebUser, ALTHOUGH I thought I had tried that first, which led me to decide to post on this blog.

I'm not sure if any of these ramblings will help anyone, but I did have the same user issue with rights, and now it's working.

Derp

The error The table "users" for active record class "User" cannot be found in the database. was caused by

'tableUsers' => 'users',
'tableProfiles' => 'profiles',
'tableProfileFields' => 'profiles_fields',

brought over from the sample 1.8 project. Derp! I'll spend more time before posting. next time. Thanks again for the guide!

Glad you got it figured out.

Glad you got it figured out. Thanks for reading!

Hello Derp You Solve the

Hello Derp

You Solve the problem, to the my is equal, the don solved.

Thank You

After struggling for nearly 3 days trying to figure things out using documents available online, your article was a life saver.

Thank you very much...

One more thing guys...I want

One more thing guys...I want to log and evaluate accesses from the database, how do I do this?

look at these tables

Check out AuthItem and AuthItemChild.

I have managed to install

I have managed to install user and rights modules...I want to be able to see in a log file, when I log in as a demo/demo, what's logged?

Is there any module that I am supposed to install for the logging? I am new to Yii.

Hello Benjamin, I have two

Hello Benjamin,

I have two problems associated with Yii.

1. I have managed to install everything successfully together with generating crud operations for the models. However, When I try to change layout of the action in the controller, the operations disappear, any suggestion for this?

2. If I want to control access to employee sensitive records (stored in employee table) using Rights module where users are stored in users table...how do I link between these two tables?

I am new to Yii and programming, I am trying to make an example for my own.

Sorry

Hi there Zuri, I'm sorry but I don't have enough info to be able to help you out. Are you checking to make sure you have the same html content in your new view as you do in your old view?

In regard to your security question, all user-generated requests are handled by a controller, and you should be using the Rights module to create an operation for each action in your controller. You can then control what roles are able to access these operations.

One more thing... Is it

One more thing...

Is it possible to use temporal constraints in access rules in Yii?

No idea

I don't quite know what you mean -- do you want a user's access to an operation change after a certain time period? As far as I know that is not possible with the module as it currently exists.

What I meant was, you have

What I meant was, you have different contexts that you can use to control access such as roles, expressions, actions(actionIDs) etc. Is it possible to use time/specify time as one of the contexts in access rules?

Nope

Sorry, as far as I know, that is not currently an option with this module. You may want to either extend it, or get in touch with the creators.

On second thought, you might

On second thought, you might be able to do this with a business rule (see the "bizrule" column in the AuthItem and AuthAssignment tables. I suggest digging into the rights module code, and also look at CDbAuthManager.php and CWebUser.php in the Yii /framework/web/auth directory.

Returning Parameters from yii users

Does anyone have an example of how to return user first name, lastname or even just the user name in a cgridview that isn't already part of the module. For example I have a worklog page with a CGridView. Right now it returns user_ids but I'd like to show username at least instead or firstname then last name. For some reason the syntax I use to get that information in other gridviews is failing. for example:

<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'worklog-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
//'id',
'user_id',
array('name'=>'user_id', 'header'=>'User', 'value'=>'$data->user->username'),

....

I get :

include(users.php): failed to open stream: No such file or directory
in yii-1.1.12.b600af/framework/YiiBase.php(423)

in my worklog model i do have

'user' => array(self::BELONGS_TO, 'users', 'user_id'),

in the relations to set up the foreign key so I'm not sure whats going on.

Does anyone have a working example of how to pull user attributes correctly in cgridviews that aren't in the user module?

Few things

I do have this working, and there are a couple things you make sure you're doing.

First, in your config file (most likely main.php), in the 'import' section, make sure you have the following lines:

'import'=>array(
 ...
 'application.modules.user.*',
 'application.modules.user.models.*',
 'application.modules.user.components.*',
 ...
)

Then, update your User model (/webapp/protected/modules/user/models/User.php):

- Add two public attributes:

public $cFirstName;
public $cLastName;

- Add the following lines in your search() function:

$criteria->addSearchCondition("profiles.firstname",$this->cFirstName,true);
$criteria->addSearchCondition("profiles.lastname",$this->cLastName,true);

- Also in the search() function, add these lines to your 'sort' attributes:

$sort->attributes = array(
 ...
 'cFirstName'=>array(
    'asc'=>'profiles.firstname asc',
    'desc'=>'profiles.firstname desc',
 ),
 'cLastName'=>array(
    'asc'=>'profiles.lastname asc',
    'desc'=>'profiles.lastname desc',
 ),
 ...
);

Finally, in your view add the CGridView as such:

<?php $this->widget('zii.widgets.grid.CGridView', array(
 'dataProvider'=>$model->search(),
 'filter'=>$model,
 'pager'=>'LinkPager',
 'columns'=>array(
    array(
      'name' => 'id',
      'type'=>'raw',
      value' => 'CHtml::link(CHtml::encode($data->id),array("admin/view","id"=>$data->id))',
    ),
    array(
      'name' => 'username',
      'type'=>'raw',
      'value' => 'CHtml::link(CHtml::encode($data->username),array("admin/view","id"=>$data->id))',
    ),
    array(
      'name'=>'email',
      'type'=>'raw',
      'value'=>'CHtml::link($data->email, "mailto:" . $data->email, array("title"=>$data->email, "target"=>"_blank"))',
    ),
    array(
      'name'=>'cFirstName',
      'value'=>'$data->profile->firstname',
    ),
    array(
      'name'=>'cLastName',
      'value'=>'$data->profile->lastname',
    ),
    ...
 ),
)); ?>

FIgured it out - my relation

FIgured it out - my relation was wrong:

'user' => array(self::BELONGS_TO, 'users', 'user_id'),

should have been

'user' => array(self::BELONGS_TO, 'User', 'user_id'),

now in a cgridview I can get to my profile fields:

array('name'=>'user_id', 'header'=>'Firstname', 'value'=>'$data->user->profile->first_name'),

One more thing need be done.

You need change last two lines in user/data/schema.mysql.sql as follow, then user and rights will work properly.
from
(1, 'lastname', 'Last Name', '...
(2, 'firstname', 'First Name', ...
to
(1, 'last_name', 'Last Name', '...
(2, 'first_name', 'First Name', ...

rights

dear i have installed rights module, now i am able to create task, role, permission and assignments.

Please tell me now how i can implement assigned role to specific controller, i have try all things which you and others has posted.

suppose i want to prevent my controller function "create" from staff member, how can i do this. please tell me i shall be thankful to you

BizRule to view only owned items

Hi Ben,

great tutorial, thanks, I've used it along with many other resources to get things work as expected. And thing did work as expected up to when I've introduced a BizRule to limit users access to their own items only.

To do this I've:
- set 'enableBizRule' to true in rights
- created a specific action ('Pubview') for my Item controller which users with role 'Customer' can execute
- created a Task ('accessOwnItems') with a BizRule as
return Yii::app()->user->id==$params["item"]->customer_id;
- set the task as child of role 'Customer'
- set the 'Pubview' action as child of task
- make sure my users have the role 'Customer' assigned
- in my ItemController's actionPubview , check for permissions as

$model=$this->loadModel($id, 'Item');
$params=array('item'=>$model);
if(Yii::app()->user->checkAccess('accessOwnItems',$params) || Yii::app()->user->checkAccess('Admin'))
$this->render('pubview',array('model'=>$this->loadModel($id, 'Item')));
else
throw new CHttpException(404,'The specified item cannot be found.');

Well, it seems I'm missing something 'cause the above always throw the exception. Everything else works fine, in terms of allowing/denying items to logged in users.
Any idea, experience, suggestion...?

Thanks again,
rash*

BizRule problem solved

Hai again Ben,

first of all, I had an error in my BizRule (I wrote 'Yii::app->user...' instead of 'Yii::app()->user...').

Then, after deeper searching, I've realized it's much DRY-er and functional to use a filter in my controller, instead of checking directly in each action.
To this, Ive modified my controller code as this:

public function filters() {
return array(
'OwnItemsAccess+ Pubview Pubupdate', // add the filter only to these two actions
'rights',
);
}

public function filterOwnItemsAccess($filterChain) {

$id = Yii::app()->request->getParam('id'); // load current model
$model=$this->loadModel($id, 'Item');
$params=array('item'=>$model); // set params array for Rights' BizRule

if(Yii::app()->user->checkAccess('accessOwnItems',$params) || Yii::app()->user->checkAccess('Admin'))
$filterChain->removeAt(1); // if everything's ok, remove the filter
else
throw new CHttpException(404,'The specified item cannot be accessed due to permissions.');
$filterChain->run(); // keep on running filters
}

This has the enormous advantage of leaving unmodified my code for the involved actions.
More, I suspect this *has* to be the right way of doing things.
And it works!

Hope this may help someone else!
Cheers,
rash*

Thanks!

Hi Rash, thanks so much for your incredibly detailed comments! It's already helpful for me, and I'm sure other people will find it helpful as well.

Best regards,
Ben

Synchronizing action rights with menu visibility

Hi, Ben. Thanks for this tutorial. I've been using RBAM rather than rights, but the results amount to the same thing. (Actually thinking of upgrading to the new auth from the author of rights.)

My question for you and followers of this thread is one I haven't been able to find discussed anywhere in the yii forums or wikis. I have permission rules in my site's controllers that prohibit some users from performing some actions. In order to simplify the site's main navigation and prevent non-admin users from getting 403 errors when they try to do things that are prohibited, I have to manually enforce the same permission rules using the 'visibility' attribute in the site-wide menu.

This is time-consuming and error-prone. Is there a way to specify menu configurations so that a controller action prohibited to the current user will automagically be hidden? (I don't believe so.) How have others worked around this need to maintain two bits of code to keep them in agreement?

subclass CMenu?

Hi Steve, I feel your pain! I also have to set each menu item's visibility via a $user->checkAccess() call in my CMenu widget. I imagine you could subclass CMenu and have it perform some automatic access checks (unless otherwise specified) for each menu item. Check out preFilter() in rights/components/RightsFilter.php for some guidance, maybe? If you do try it out, please let me know what you find!

Maybe call preFilter on the controller action

Thanks for mentioning the preFilter method. It had dawned on me that the controller must somehow encapsulate a method to make the permission decision. Some very quick research uncovered the filterAccessControl method of CController, which is a more complete way to specify controller access rules, compared to the usual accessRules array. Apparently the array is a shortcut, but if you override it in a controller, you can create a full-blown CAccessControlFilter object encapsulating the same rules and also providing the preFilter method. Theoretically it should be possible somehow to invoke prefilter in the menu visibility code, which would at least put the rules in one place rather than two. I'll take a look at the file you mentioned to see if there's code that does anything similar. (As with most of the Yii documentation, I find these class and method descriptions too concise for me to grasp exactly how to implement them without seeing examples. As I work more with Yii I'm gradually getting better at reading between the lines!)

There's already an extension!

And a little more research reveals that user sidtj has already created the yiismartmenu extension, which does exactly what we're talking about. Apparently it works with the rights extension out of the box, but not with yii's built-in rbac, though there are ways to adapt it. (I didn't realize until reading the yiismartmenu docs that rights doesn't merely provide a front end for rbac.)

This is helpful, but on another note, I learned yesterday that I'm going to have to implement a more complex solution for one of my clients. The requirement is not to hide all menu items for which the user doesn't have permission, but rather to show some of them grayed out and display a pop-up information dialog when they're clicked or hovered over. That obviously adds a whole additional layer of complexity. It's a great idea, though, for upselling optional extra-cost components of a web-based service. At least I'll have the yiismartmenu code to help guide me.

thanks!

That's so rad, thank you for follow-up! Best of luck with your continued dev work.

Take a look at my YII demo app

Hi Steve,
Take a look at my demo app(DL) hosted on GitHub at https://github.com/Krish-Chandra/DL.git. It uses SRBAC YII extension for RBAC.
It has the following features, among others:
1. Role-based access control
2. Admin UI component to manage roles, tasks, and operations and assign them to users
3. Display menu items dynamically based on logged-in user's rights(doesn't use CMenu but instead displays the menu items in tabs generated dynamically)
4. Migrations to move from one version of the app to another

Read the README file to see the features implemented in the app. Check out the 'Use-YII-RBAC' branch to see how RBAC works. It may not be exactly what you are looking for, but I am sure it will at least give you some pointers, in case you are still looking for one.

Thanks!

Thanks a lot, Krish. I'll take a look. I've been trying out the YiiSmartMenu extension. It works as advertised, but it sure is slow. There has to be a better way.

Error message RWebUser

Hi, I am working with yii for the first time and trying to install users and rights extension is proving more difficult than it should... I have followed all of the instructions above and it isn't working as I would expect. I am getting the following error relating to the user module

include(RWebUser.php) [function.include]: failed to open stream: No such file or directory

if I comment out the 'class'=>'RWebUser' line then I dont get an error but the users module is not working.

Also I cant seem to install the rights module using the installer - my browser shows a 'file not found' message. can someone please shed some light on this for me? I am new to yii and not too sure what the problem is here...

Dealing with the error message first

Did you include the application.modules.rights.* and application.modules.rights.components.* lines in your import directive in the main.php config file?

Synchronizing action rights with menu visibility

Hi Steve,
Take a look at my demo app(DL) hosted on GitHub at https://github.com/Krish-Chandra/DL.git. It uses SRBAC yii extension for rights management, displaying menu items based on logged-in user's rights, database migrations, etc. In particular, take a look at the 'Use-YII-RBAC' branch.

Cmenu items filter and access

Hi. I am new to YII.
Thanks for perfect tutorial on installing this components. I installed them thanks to you.
I have 2 problems.
1. I have admin and tester accounts. I want to hide and show Cmenu item depending on user name, how to do this using rights or user components.

2. I added Employee item to menu for tester user by using checkAccess(''), but when i click on this item it throws error "Error 403 You are not authorized to perform this action.".

Need your help.

Use "visible" attribute

Hi İlqar, you can use the "visible" attribute on each CMenu item to determine whether or not to show them. See my examples above.

As for your other question, my guess would be that you haven't yet created an operation for this "Employee" controller action. Remember, if you're using Rights to determine controller action access, you have to explicitly state which roles or users can perform that action (except the superuser - he can do all actions).

Thanks

Thanks, it worked. Just removed roles and permissions and created new ones, perhaps i did something wrong.
And another question, at first highlighting active page menu items didn`t work. I used "active" state attrribute to solve problem. This solution working for all menu items execpt "Rights".
array('label'=>'Rights', 'url'=>array('/rights'), 'visible'=>Yii::app()->user->checkAccess('Rights menu item'),
'active'=> (strcasecmp($this->id, 'rights') === 0) ? true : false)
What can I do.

comparing with wrong Id

The Id in this case is "assignment," so your comparison should look like strcasecmp($this->id, 'assignment').

This is because by default, the full path being executed when you navigate to /rights is /rights/assignment/view. Check out this block in RightsModule.php:

// Normally the default controller is Assignment.
$this->defaultController = 'assignment';

About comment system

sorry for disturbing you ,i'm developer in yii ,when we loocking for a extension of yii,i see this.yes,your comment system looks well and it is fit for our requirements.so ,can you told me about how to acheve this ,my partner and i want to have a think of how to do a comment ,maybe a liitle,we want to see more references .forgive me for my poor engnish.thanks(will you contact me via email,much better)

this is a drupal site

Hi there, sorry, but this site is built in Drupal. You might want to check out this or this comment module for Yii.

db backup

Great tutorial !!!

can you please provide db backup to your github page
https://github.com/benjaminlhaas/Yii-with-Users-and-Rights

it will be helpfull !!

Thanks in advance...

run the migrations!

Thanks for the nice words. In regard to the db backup -- I'd rather let each user run the migration scripts -- it's an important part of learning to use Yii!

Error in rights

Hi,
When i got to this url : webpath/rights/

I get this error:

Error

An error occurred while installing Rights.

Please try again or consult the documentation.

but in my database created 3 tables: AuthAssignment, AuthItem and AuthItemChild

what can i do?

permissions?

Is it possible that your mysql user has "create" permissions but not "insert" permissions? If you look in /rights/components/RInstaller.php::run(), you can see that the install procedure creates the tables, then tries to insert data in them.

Schema for 'user' table has

Schema for 'user' table has been updated by author, you can remove 'optional' step :)

thanks

Great, thanks for the update!

error bootstrap extension

hi, i am using the bootstrap extension and i have installed Yii Users and Rights. I am having error when login.
Below the error message:
return Yii::app()->getModule('user')->tableUsers;
do you know how to solve this problem? without bootstrap all works like a charm.

Unfortunately I can't help

Unfortunately I can't help you as I haven't tried this with Bootstrap, but I'm hoping another reader can pitch in.

A Perfect tuts for start up guy in Yii Framework

Thanks buddy. Thanks alot

:-)

:-)

error when delete user

when im in manage user (webroot/index.php?r=user/admin) and delete one user, i can't delete
Error 400
Invalid request. Please do not repeat this request again.

help me

look for error in controller

If you look in modules/user/controllers/AdminController.php, at the method actionDelete(), you'll see that this exception is most likely thrown because you are not submitting a POST request. This is the code:

public function actionDelete()
{
   if(Yii::app()->request->isPostRequest)
   {
      ...
   }
   else
      throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
}

Great insight for my first

Great insight for my first ever Yii Extension install

Hello, how to disable a

Hello, how to disable a registration with yii-user???

Thanks for the github

Thanks for the github project. Easier to learn when there is complete sample

Hi, I want change and set

Hi,
I want change and set tablePrefix for all tables(users, AuthAssignment, AuthItem, AuthItemChild, Rights,...)
what i must do?

config setting

Hi, I do that but when I open

Hi,
I do that
but when I open my website, I receive this error: Property "UserModule.rights" is not defined.

Yes I do that but after

Yes I do that
but after this(and add perfix to all tables in my database),
When open my website, i recieved this error: The table "users" for active record class "User" cannot be found in the database.

Did you try skipping step 3

Did you try skipping step 3 in the instructions above? If that didn't work, did you try specifying the correct table name in the 'user' section of config/main.php?

Starting Fresh

Hi,

I'm a developer who is new to Yii, and I've been trying to decide whether to build my own membership and permissions system or use these extensions.

I notice that there have been no recent updates.

The last update on the change log for Yii rights is "April 1, 2011".
The last update on the change log for Yii-user is "2012-06-11".

Given that these extensions are not being regularly updated, I have a degree of pessimism about using them.

I would rather develop my own solution from scratch than spend days or weeks trying to solve obscure bugs in a defunct, unsupported add-on.

On the other hand, I'm keen not to re-invent the wheel.

Your thoughts?

(: Hereward

good questions

I totally understand where you're coming from, and wholeheartedly sympathize. :-)

Do I think these extensions are flawed? Yes. Do I wonder why they haven't been updated within the past three years? Yes. Are they still the best (and most supported within the community) out there? Probably.

For the most part, I would say that these extensions are very solid, and therefore don't need to be updated. Mostly, they do an excellent job of implementing a user and rights framework, giving lots of leeway to individual developers to customize to their needs. That isn't to say, though, that I think they're perfect.

I wish the user extension uses bcrypt instead of md5 (and in fact there is a one-year-old outstanding pull request for this, https://github.com/mishamx/yii-user/pull/19, which suggests that the original author is no longer involved.

I wish the rights extension didn't make so many database calls when checking a nested permission, especially when there are lots of rights checks per page. But then again, this is trivially handled by caching, such as APC.

I have heard good things about the auth extension, as a replacement for the rights extension, but I haven't tried it. http://www.yiiframework.com/extension/auth/

Best of luck to you!

Great and Usefull

Nice one...

Error

Error

An error occurred while installing Rights.

Please try again or consult the documentation.

Finally it is working fine..

Make sure before installing rights Open the yii-user mysql schema (located at /webapp/protected/modules/user/data/schema.mysql.sql only and rest of the tables and data is updated while installing rights.. Use some time to figure it out, may be useful for somebody..

Thanks for the nice tutorial..

Thanks! Very good!

Thank you very good!

Works (almost) perfectly

Works (almost) perfectly.

- before going to /rights you need to login through /user/login and you will get an error page (but it's ok. you are logged in)
- after installing 'rights' the link in the success page was (in my browser) not clickable. If you have the same issue just go to /rights/authItem/generate
- you would to generate items for all the controllers/actions that will need to be filtered by role/user (remember that you could visit /rights/authItem/generate many times). Defenitely you would generate items for UserModule
- some editing of recovery.php registration.php and login.php for bootstrap usage.

Good Work. Thanks!

Same to you

Thanks for the feedback and follow-up!

Thank you very much for your

Thank you very much for your help!

Works like charm

This is great. I was struggling with this more than one day. But finally this tutorial made my day.

Thanks a lot. Great work. :)

thanks

Thanks You!

My english is not very

My english is not very good.

I need to know how to put the right module in my theme.
By default this module uses the default theme yii and I need to change it to my theme.

Thanks.

config setting

You set the theme in main.php, like the following:

'theme'=>'my_theme_name'

Thank you do not understand.

Thank you do not understand. I already have the theme running but when trying to access the right module it loads the default interface of yii.

Ah, I understand you now. You

Ah, I understand you now. You might want to check out setting the $appLayout config variable in modules/rights/RightsModule.php. For example, you might want it to look something like the following:

public $appLayout = 'webroot.themes.my_theme.views.layouts.main';

ben sorry but I can not put

ben sorry but I can not put the webroot.
am new in yii framework.

Hi Marcos, I wish I had more

Hi Marcos, I wish I had more advice, but unfortunately I am not sure how to help you any further. Perhaps someone else reading this can be of assistance.

alright ben anyway thanks for

alright ben anyway thanks for the help

Error on install rights

When install with http://local.administrador/index.php?r=rights/install i get the error
Alias "rights.RightsModule" is invalid. Make sure it points to an existing PHP file and the file is readable.

config/main.php is ok

Do you have any success if

Do you have any success if you navigate to http://local.administrador/rights, with the "install" flag set to true in your config?

I found a good alternative to

I found a good alternative to the yii right.
useradmin - http://www.yiiframework.com/extension/useradmin/

Great Thanks

Thanks god,
u save my life... :)
I've already installed with your clear Help!!
thanks again

gbu,

Thanks for the GitHub

Thanks for the GitHub repository. This helped a lot.

Hello friends the error

Hello friends

the error ocurred in my project.

Active record "User" is trying to select an invalid column "user.lastvisit_at"

please my help

thanks

hello

Hello

follow error code

Active record "User" is trying to select an invalid column "user.lastvisit_at". Note, the column must exist in the table or be an expression with alias.

please help

Please see step 3.1 in my

Please see step 3.1 in my post above.

thnx

thanx bro you solved my problem

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
4 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.