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 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.

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.

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