[Module] Yii User Management Module

Hi,

Found a couple of bugs in 0.4:

ERROR: Property "CWebUser.registrationUrl" is not defined.

In views/user/login.php on line 42 you need to change the line like this:


<?php echo CHtml::link(Yii::t("UserModule.user", "Registration"),Yii::app()->User->registrationUrl); ?> | <?php echo CHtml::link(Yii::t("UserModule.user", "Lost Password?"),Yii::app()->User->recoveryUrl); ?>

Note the uppercase ‘u’ in ‘User’ - Yii::app()->User->registrationUrl

ERROR: CWebUser does not have a method named "isAdmin".

There are similar errors in views/user/myprofile.php on line 14, 15 and 16:

Change to this:


array('label'=>Yii::t('UserModule.user', 'Manage User'), 'url'=>array('admin'), 'visible' => Yii::app()->User->isAdmin()),

array('label'=>Yii::t('UserModule.user', 'Manage Roles'), 'url'=>array('role/admin'), 'visible' => Yii::app()->User->isAdmin()),

array('label'=>Yii::t('UserModule.user', 'List User'), 'url'=>array('index'), 'visible' => !Yii::app()->User->isAdmin()),

There may be others, not checked everything yet.

Edit:

Updating this as I go along…

views/user/profile-edit.php has the same errors on lines 15 and 20.

Just change to Yii::app()->User->isAdmin()

Also similar error littered throughout controllers/UserController.php

Different bugs in models/UserLogin.php

Line 69 change ERROR_STATUS_NOTACTIV to ERROR_STATUS_NOTACTIVE

Line 72 change ERROR_STATUS_BAN to ERROR_STATUS_BANNED

thanks for reporting, the wrong constants have been fixed in svn.

the Yii::app()->user should work without uppercase U. Are you using the latest yii-1.1.1 ?

I’m using latest Yii-1.1-dev from SVN, updated today.

I did wonder if I had done something wrong because I thought there was no way you could have missed those uppercase errors.

My config seems correct though according to the tutorial and I didn’t get those errors before I updated to 0.4.


// autoloading model and component classes

    'import'=>array(

        'application.modules.user.models.*',

        'application.models.*',

        'application.components.*',

    ),


    'modules' => array(

        'user' => array(

            'debug' => false,

        ),

    ),


    // application components

    'components'=>array(

        'User'=>array(

            'class' => 'User',

        ),


        'user'=>array(

            'allowAutoLogin'=>true,

            'loginUrl' => array('/user/user/login'),

        ),


        'urlManager'=>array(

            'urlFormat'=>'path',

            'showScriptName'=>false,

            'rules'=>array(

                '<controller:\w+>/<id:\d+>'=>'<controller>/view',

                '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',

                '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

            ),

        ),

The only thing I didn’t do was use your installer, however I completely deleted the ‘user’ module, put back the proper UserIdentity.php component and made the necessary changes to config.

I’m also developing on Windows with PHP 5.3 if that makes a difference?

By the way, I think I found another bug in the UserController.php

Line 195 reads: if (($uid = Yii::app()->user->id) === true)

But I think it should probably be: if (($uid = Yii::app()->user->id) == true)

Also I have commented out line 319: $profile->attributes=$_POST[‘Profile’];

because it causes Error 500, No Index ‘Profile’.

And more…

The password recovery needed a little work since it displayed the whole message including the url, in the subject field.

The ‘setFlash()’ variable was also wrong.

I have changed lines 266 and 267 to the following:




mail($user->email,"Password Reset Request", "You have requested to be reset. To receive a new password, go to $activation_url.",$headers);

Yii::app()->user->setFlash('recoveryMessage',Yii::t("user", "Instructions have been sent to you. Please check your eMail."));

Same on line 100:


mail($model->email,Yii::app()->name. " Registration","You registered from " . Yii::app()->name,"Please activate your account go to $activation_url.",$headers);

This change to views/user/recovery.php on line 3 makes it pretty much bug-free (for me at least) :)




Yii::t("UserModule.user", "Login") => array('/user/user/login'),

Crosses fingers.

All changes are in the attached zip file.577

user.zip

Small bug in UserIdentity.php line 30:

Change ‘$logintype’ to ‘$loginType’

I have a couple of issues setting things up.

One of them is that I had the same problem as outrage in that I needed to change all references to "user" to "User". We have very similar config files though, so has anyone seen anything in his posted main.php file that would cause those issues?

Also, I can’t seem to get any of the links that reference ‘user/admin’. I need to change it to ‘user/user/admin’ in order to get it to work. I’ve posted my main.php file below, what can I change to fix these problems I’m having? I’m extremely new to Yii, so please, be gentle :slight_smile:




<?php


// uncomment the following to define a path alias

// Yii::setPathOfAlias('local','path/to/local-folder');


// This is the main Web application configuration. Any writable

// CWebApplication properties can be configured here.

return array(

	'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',

	'name'=>'My Web Application',

    'modules' => array(

        'user' => array(

          'debug' => true

        ),

    ),




	// preloading 'log' component

	'preload'=>array('log'),


	// autoloading model and component classes

	'import'=>array(

		'application.models.*',

		'application.components.*',

        'application.modules.user.models.*',

	),


	// application components

	'components'=>array(

	    'User'=>array(

            'class' => 'User',

        ),

	

		'user'=>array(

      		'allowAutoLogin'=>true,

      		'loginUrl' => array('/user/user/login'),

        ),

        

		// uncomment the following to enable URLs in path-format

		'urlManager'=>array(

			'urlFormat'=>'path',

			'rules'=>array(

				'<controller:\w+>/<id:\d+>'=>'<controller>/view',

				'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',

				'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',

			),

		),


		'db'=>array(

			'connectionString' => 'mysql:host=localhost;dbname=xxx',

			'emulatePrepare' => true,

			'username' => 'xxx',

			'password' => 'xxx',

			'charset' => 'utf8',

		),

		'errorHandler'=>array(

			// use 'site/error' action to display errors

            'errorAction'=>'site/error',

        ),

		'log'=>array(

			'class'=>'CLogRouter',

			'routes'=>array(

				array(

					'class'=>'CFileLogRoute',

					'levels'=>'error, warning',

				),

				// uncomment the following to show log messages on web pages

				/*

				array(

					'class'=>'CWebLogRoute',

				),

				*/

			),

		),

	),


	// application-level parameters that can be accessed

	// using Yii::app()->params['paramName']

	'params'=>array(

		// this is used in contact page

		'adminEmail'=>'webmaster@example.com',

	),

);



Using Yii Version 1.1.1, and the latest release of user v0.4 (not the svn).

Thanks!

Hello, I can’t install module on clean webapp.

Getting “The table “users” for active record class “User” cannot be found in the database.” when i’m trying to run /index.php?r=user/install or /index.php?r=user/user/install. Please help.

module v0.4

yii 1.1.1.r1907




Stack Trace


#0 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\db\ar\CActiveRecord.php(329): CActiveRecordMetaData->__construct(Object(User))

#1 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\db\ar\CActiveRecord.php(342): CActiveRecord::model('User')

#2 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\db\ar\CActiveRecord.php(59): CActiveRecord->getMetaData()

#3 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\YiiBase.php(205): CActiveRecord->__construct()

#4 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\base\CComponent.php(302): YiiBase::createComponent(Array)

#5 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\base\CComponent.php(271): CComponent->attachBehavior('User', Array)

#6 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\base\CApplicationComponent.php(45): CComponent->attachBehaviors(Array)

#7 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\auth\CWebUser.php(161): CApplicationComponent->init()

#8 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\base\CModule.php(352): CWebUser->init()

#9 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\base\CModule.php(86): CModule->getComponent('user')

#10 H:\a\UniServer\www\tester\tester\protected\views\layouts\main.php(34): CModule->__get('user')

#11 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CBaseController.php(119): require('H:\a\UniServer\...')

#12 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CBaseController.php(88): CBaseController->renderInternal('H:\a\UniServer\...', Array, true)

#13 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\widgets\CContentDecorator.php(78): CBaseController->renderFile('H:\a\UniServer\...', Array, true)

#14 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\widgets\CContentDecorator.php(56): CContentDecorator->decorate('<div class="con...')

#15 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\widgets\COutputProcessor.php(45): CContentDecorator->processOutput('<div class="con...')

#16 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CBaseController.php(193): COutputProcessor->run()

#17 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CBaseController.php(288): CBaseController->endWidget('CContentDecorat...')

#18 H:\a\UniServer\www\tester\tester\protected\views\layouts\column1.php(7): CBaseController->endContent()

#19 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CBaseController.php(119): require('H:\a\UniServer\...')

#20 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CBaseController.php(88): CBaseController->renderInternal('H:\a\UniServer\...', Array, true)

#21 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CController.php(683): CBaseController->renderFile('H:\a\UniServer\...', Array, true)

#22 H:\a\UniServer\www\tester\tester\protected\modules\user\controllers\InstallController.php(154): CController->render('start')

#23 H:\a\UniServer\www\tester\tester\protected\modules\user\controllers\InstallController.php(163): InstallController->actionInstall()

#24 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\actions\CInlineAction.php(32): InstallController->actionIndex()

#25 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CController.php(300): CInlineAction->run()

#26 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CController.php(278): CController->runAction(Object(CInlineAction))

#27 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CController.php(257): CController->runActionWithFilters(Object(CInlineAction), Array)

#28 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CWebApplication.php(320): CController->run('')

#29 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\web\CWebApplication.php(120): CWebApplication->runController('user/install')

#30 H:\a\UniServer\www\tester\yii-1.1.1.r1907\framework\base\CApplication.php(135): CWebApplication->processRequest()

#31 H:\a\UniServer\www\tester\tester\index.php(12): CApplication->run()

#32 {main}






Found a bug in UserController.php on the ‘create’ action.

Roles were not being added at creation.

Add the following line below “if (isset($_POST[‘User’])) {”


$model->roles = $_POST['User']['Role'];

first of all give you my most sincere congratulations for your work that you’re doing.

One question: Is it possible to combine yii-user-management with the Srbac?

Thanks a lot.

Yes, it is possible to use yii-user with srbac. Just install both modules and assign them the same ‘usersTable’.

You can override/extend the User Model provided by Yii User Management module by adding up your own in models/User.php

and set them below the include of modules/models/User.php.

Yii user 0.5, which will be released soon, contains a very lot of bugfixes and code cleaning. If you had problems

with 0.4, you will have a great chance that your problem is solved. Here’s the changelog (so far):

the submodularizing seems to be running good. You now can toggle the profiles, messaging system and role manager on&off in the config.

please test this release so we can go onwards to a "stable" 1.0 release soon!!!

@lostmahbles:

/user/user/login is the correct path. It’s module/controller/view.

when you want to use user/login you have to create a rewrite Rule.

Read about this in the yii docs or wait for my next tutorial which will cover this topic, thank you ;)

@ssh:

are you using mysql and if yes: which version? does your db connection work fine?

@thyseus:

Awesome extension.

Really helped me learn & made it easy to implement RBAC which I was having a hard time with.

I have a requirement of emailing notifications to users having specific roles upon certain actions e.g. upon actionCreate in one of my controllers.

While I have worked out sending email notifications, I can not seem to get around getting users emails pulled based on roles. How can I pull emails of all users having a certain role?

For that matter maybe its possible to add a function/method in the "Role" model for pulling up specific user attribute (e.g. email or username) for the given role(s).

Something like:




public static function getUserAttributeByRole($attribute,$roles){


if(!is_array($roles))

    $roles = array ($roles);


if(!is_array($attribute))

    $attribute = array ($attribute);

		

foreach($roles as $role) 

      {

      // find users having that $role

      // pull required $attribute from users

      // add to return array

      }

}



Maybe I am making it more complicated than it should be so any pointers welcome.

I have installed this great extantion successfuly, but don’t understant, how can i get value of field in profile that i need from any place in my site??? like this:

Yii::app()->user->id

but i want

Yii::app()->user->email

Yii::app()->user->city

Yii::app()->user->gender etc … help me please

or may be some thing like

User::model()->profile($id)->email;

i dont know =(

I managed to obtain emails by adding a function in model ‘Role’




	public static function getEmailsByRole($roleTitles)

	{

		if(!is_array($roleTitles))

			$roles = array ($roleTitles);

		foreach($roleTitles as $role->title) 

		{

			$find = Role::model()->findByAttributes(array('title'=>$role->title));

			$users = Role::model()->findbyPk($find->id)->getRelated('users');

			foreach($users as $user)

				{

					$return_emails[] = $user->email;

				}

		}

		sort($return_emails);

		$return_emails = array_unique($return_emails);

		return $return_emails;

	}	



Usage Example:




$emails = Role::model()->getEmailsByRole(array('admin','demo'));



Hope this helps someone having similar need.

Hi!

What do you think about this:


public function beforeControllerAction($controller, $action)

{

	if(parent::beforeControllerAction($controller, $action))

	{

		return true;

	}

	else

		return false;

}

VS


public function beforeControllerAction($controller, $action)

{

	return parent::beforeControllerAction($controller, $action);

}

And there is a patch:


Index: UserModule.php

===================================================================

--- UserModule.php      (revision 10)

+++ UserModule.php      (working copy)

@@ -3,18 +3,19 @@

 class UserModule extends CWebModule

 {


-       public $version = '0.4';

-       public $debug = false;

-       public $usersTable = "users";

-       public $messagesTable = "messages";

-       public $profileFieldsTable = "profile_fields";

-       public $profileTable = "profiles";

-       public $rolesTable = "roles";

-       public $userRoleTable = "user_has_role";

-       public $installDemoData = true;

-       public $layout = 'column2';

-       public static $dateFormat = "m-d-Y";  //"d.m.Y H:i:s"

+       public $version              = "0.4";

+       public $debug                =  false;

+       public $usersTable           = "users";

+       public $messagesTable        = "messages";

+       public $profileFieldsTable   = "profile_fields";

+       public $profileTable         = "profiles";

+       public $rolesTable           = "roles";

+       public $userRoleTable        = "user_has_role";

+       public $installDemoData      =  true;

+       public $layout               = "column2";


+       public static $dateFormat    = "m-d-Y";  //"d.m.Y H:i:s"

+

        // LoginType :

   // 0: Allow login only by Username

   // 1: Allow login only by E-Mail

@@ -32,11 +33,6 @@


        public function beforeControllerAction($controller, $action)

        {

-               if(parent::beforeControllerAction($controller, $action))

-               {

-                       return true;

-               }

-               else

-                       return false;

+               return parent::beforeControllerAction($controller, $action);

        }

 }

Hi I am getting same issue when installing on clean webapp.

module v0.4

yii 1.1.1.r1907

PHP 5.2.10-2ubuntu6.4 with Suhosin-Patch 0.9.7 (cli) (built: Jan 6 2010 22:41:56)

mysql Ver 14.14 Distrib 5.1.37, for debian-linux-gnu (i486) using EditLine wrapper

The termout from install

612

termout.txt

my main.php

611

main.php

http://localhost/index.php?r=user/install

gives

610

index.php.html

which is the same error.

I had a few of these issues too…but the solution is simple.

Try typing the controller/action directly in your browser address to find the yii-user login page.

In other words…

Do not login with the generated user

Let me know if this works for you

Hi

Not sure I understand you. You cannot login. The problem is that on line 154 of the InstallController.php as a precursor to installing

it says


$this->render('start');

but this uses

protected/views/layouts/main.php

which on line 34,35


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)

has references to the user class which fail and so the installer fails because it needs itself installed before installing.

Anyway I am sorted, I just commented out stuff in protected/views/layouts/main.php while installing.

hello,

I know it sounds silly but I can’t get it to work :confused:

How would I know if my logged in user is a superuser?




// i thought this should work


Yii::app()->user->superuser;


// but it's not



thanks,

–iM

Try





Yii::app()->User->superuser();




Try Yii::app()-user->isAdmin();

The source to look at is WebUser.php

@msubzwari

Looks like you are using older code.

Hey everyone!

I just silently release Yii User Management Module 0.5 which (hopefully) should solve all aforementioned problems.

The right method is called Yii::app()->user->isAdmin() or, when you want to get all admins, you use

User::getAdmins()

A user can now be the ‘admin’ for a bunch of other users (when role submodule is activated).

This goes like this:




array('allow',

          'actions' => array('admin'),

          'expression' => "Yii::app()->user->hasUsers()",

          ),

        array('allow',

          'actions' => array('update'),

          'expression' => 'Yii::app()->user->hasUser($_GET[\'id\'])',

          ),



After that, you have this new features:




 // Activate profile History (profiles are kept always, and when the 

  // user changes his profile, it gets added to the database rather than

  // updated).

  public $profileHistory = true;


  // When readOnlyProfiles is set, only administrators can update Profile

  // Information

  public $readOnlyProfiles = false;


  // When forceProtectedProfiles is set, only administrators and the user 

  // himself can view the profile 

  public $forceProtectedProfiles = false;




Thank you for mentioning my Module in the Yii Radio Show ;) I hope it gets some more users and/or contributors.

Google Code Repository still very active, and there are a lot of people who helped making this release possible! Thanks everyone. They are mentioned in the docs/changelog.txt

http://code.google.com/p/yii-user-management/