How to make authentication in module

Hello all i have a module, it’s name it administrator. I want to make user authentication for that, i have made UserIdentity in app/components/UserIdentity





<?php


/**

 * UserIdentity represents the data needed to identity a user.

 * It contains the authentication method that checks if the provided

 * data can identity the user.

 */

class UserIdentity extends CUserIdentity {

private $_id;

    /**

     * Authenticates a user.

     * The example implementation makes sure if the username and password

     * are both 'demo'.

     * In practical applications, this should be changed to authenticate

     * against some persistent user identity storage (e.g. database).

     * @return boolean whether authentication succeeds.

     */

    public function authenticate() {

        $record = LOGIN::model()->findByAttributes(array('USER' => $this->username));

        if (is_null($record)) {

            $this->errorCode = self::ERROR_USERNAME_INVALID;

        } else if ($record->PASSWORD != $this->password) {

            $this->errorCode = self::ERROR_PASSWORD_INVALID;

            $this->errorCode = self::ERROR_USERNAME_INVALID;

        } else {

            $this->_id = base64_encode($record->ID_LOGIN);


            switch ($record->HAK_AKSES) {

                case 0: $role = 'Administrator';

                    break;

                case 1: $role = 'Majelis Tinggi';

                    break;

                case 2: $role = 'Assesor';

                    break;

                case 3: $role = 'Pengusul';

                    break;

                case 4: $role = 'Tamu';

                    break;

                default:

                    $role = '';

            }


            $this->setState('role', $role);


            //$this->setState('nome', $record->nome);

            $this->errorCode = self::ERROR_NONE;

        }

        return!$this->errorCode;

    }


    public function getId() {

        return $this->_id;

    }


}




And i want call Yii::app->user->role in module admin. But i have problem

Property "CWebUser.role" is not defined

Do you have solution for my problem ?

Your code of the UserIdentity seems to be ok, so Yii::app->user->role should work if:

  • The user is really logged in. Maybe he is a guest when calling Yii::app->user->role.

  • The LoginForm.authenticate is implemented correct





	public function authenticate($attribute,$params)

	{

		if(!$this->hasErrors())  // we only want to authenticate when no input errors

		{


                   	case UserIdentity::ERROR_NONE:

					$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days

					Yii::app()->user->login($identity,$duration);

					

                                        die('role='.Yii::app()->user->role); //<--- try this      

                                        

					break;

                      

                        ....

                }

        }




extend the Cwebuser class and write all the functions in it. (call it MyWebUser)

in your config/main.php file

inside the component array, point the user to the file which you extended.




 'components'=>array(

   user'=>array(

		   'class'=>'application.components.MyWebUser'),

  )



you are done.

I have tried your solution but i get error

Property "UserIdentity.defaultController" is not defined.

is the site/login or your login action in a module??

if yes, then u need to add it to the component array in the config/main.php file.

Yes it’s true. But i want to call user->role in my module. That’s possible ?

in my ADMINModule.php





<?php


class ADMINModule extends CWebModule {


    public function init() {

        // this method is called when the module is being created

        // you may place code here to customize the module or the application

        // import the module-level models and components

        $this->setImport(array(

            'ADMIN.models.*',

            'ADMIN.components.*',

        ));


      

        $this->layout = 'admin';

        $this->setComponents(array(

            'errorHandler' => array(

                'errorAction' => 'ADMIN/default/error'),

            'user' => array(

                'class' => 'CWebUser',             

                'loginUrl' => Yii::app()->createUrl('ADMIN/default/login'),

            )

        ));

        Yii::app()->user->setStateKeyPrefix("_{$this->id}"); 

        Yii::app()->user->loginUrl = Yii::app()->createUrl("/{$this->id}/default/login");

    }


    public function beforeControllerAction($controller, $action) {


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

            // this method is called before any module controller action is performed

            // you may place customized code here

            if (Yii::app()->user->isGuest) {

                 Yii::app()->request->redirect(Yii::app()->createUrl(Yii::app()->user->loginUrl));

            } else {

               

                $controller->layout = 'admin';

                return true;

            }

        }

        else

            return false;

    }


}






i want change Yii::app()->user->isGuest to Yii::app()->user->role

As I wrote above:

Calling Yii::app()->user->role will throw the exception ‘Property “CWebUser.role” is not defined’, if the user is not logged in and is a guest. For a guest user the property role is not set, because Yii::app()->user->setState(‘role’,…) never has been called.

So you have to check:




  if (Yii::app()->user->isGuest) 

  {

    ...

  }

  else

  if (Yii::app()->user->role == 'xy') 

  {

      ....

  } 




I use Yii::app()->user->role (assigned in the UserIdentity.php like your code) in my projects too.

It works fine and it’s independent of where is called in the app (main/module/submodule …).

Prasetutama: take a look at some of the user modules available in the Yii extensions repository.

Nothing beats looking at real, working code. ;)

<edit>

This: http://www.yiiframework.com/extension/yii-user/

Hello i have tried your solution. but when i call user-> role the result it’s same Property “CWebUser.role” is not defined. You have another solution ??

Thanks but i want make my own code :)

Yes, exactly: take a look at the working code and compare it to your own code.

[color=#1C2837]CWebUser.role is not defined, of course. It should be YourUserModel.role, shouldn’t it?[/color]

[color=#1C2837]

[/color]

[color=#1C2837]There are four things working together: CWebUser, CUserIdentity, UserModel and UserController.[/color]

[color=#1C2837]Easy to get lost. :)[/color]

It’s more than four things, actually…

Be sure to read this chapter of the guide:

http://www.yiiframew.../en/topics.auth

First two sections are enough.

Oh you can show what the solution :)

Yii-user is totally simple.

It would take me far longer time to explain what happens than it would take you figuring that out by looking at it yourself.

Thanks sob :)

Pathetic help vampire.

I think i have got solution, may be i have to make login in my module and make special useridentity. I think it’s true. How about your suggestion, i’m confuse. Or i have to use RBAC ?? pleas help me, i’m stack

You don’t need to use RBAC.

You can use this:

http://www.yiiframework.com/wiki/276/simple-authorization-system/

But authorization is different from authentication. :)