Home  >  Article  >  Backend Development  >  How to add a new user verification in yii

How to add a new user verification in yii

不言
不言Original
2018-06-15 16:20:261345browse

This article is a detailed analysis and introduction to the method of adding a new user verification in Yii. Friends who need it can refer to it

1. Why should we add a new user? Verification:
Because I want to build the website backend and frontend in the same Yii application. But the frontend also contains the member management center. And the two user verifications are completely different, so Two different login pages are required, and user information must be stored in different cookies or sessions. Therefore, a user verification needs to be added to an application
2.yii user verification:
Before customizing user verification, we must first figure out the verification and authorization methods of yii.
In order to verify a user, we need to define a verification class with verification logic. This class needs to be implemented in yii IUserIdentity interface, different classes can implement different verification methods. Website login generally needs to verify the user name and password. Yii provides the CUserIdentity class, which is generally used to verify user names and passwords. After inheritance, we need to rewrite it authenticate() method to implement our own verification method. The specific code is as follows:
Php code

class UserIdentity extends CUserIdentity  
{  
    private $_id;  
    public function authenticate()  
    {  
        $record=User::model()->findByAttributes(array('username'=>$this->username));  
        if($record===null)  
            $this->errorCode=self::ERROR_USERNAME_INVALID;  
        else if($record->password!==md5($this->password))  
            $this->errorCode=self::ERROR_PASSWORD_INVALID;  
        else 
        {  
            $this->_id=$record->id;  
            $this->setState('title', $record->title);  
            $this->errorCode=self::ERROR_NONE;  
        }  
        return !$this->errorCode;  
    }  
    public function getId()  
    {  
        return $this->_id;  
    }  
}

When the user logs in, the following code is called:

Php code

// 使用提供的用户名和密码登录用户  
$identity=new UserIdentity($username,$password);  
if($identity->authenticate())  
    Yii::app()->user->login($identity);  
else 
    echo $identity->errorMessage;


When the user exits, the following code is called:
Php code

// 注销当前用户  
Yii::app()->user->logout(); 
 其中的user是yii的一个components.需要在protected/config/main.php中定义

Php code

'user'=>array(  
    // enable cookie-based authentication  
    'allowAutoLogin'=>true,  
        'loginUrl' => array('site/login'),  
),

Here we did not specify the class name of user. Because in Yii, user is an instance of the CWebUser class by default.
We have now implemented user login verification and logout. But now whether the user is logged in or not, the user All actions can be accessed, so the next step is to authorize user access. In Yii, user authorization is achieved through the Access Control Filter. Let’s take a look at a simple Controller with access control:
Php code

class AdminDefaultController extends CController  
{   
    public function filters()  
        {  
            return array('accessControl');  
        }  
        public function accessRules()  
        {  
            return array(  
                array(  
                    'allow',  
                    'users' => array('@'),  
                ),  
                array(  
                    'deny',  
                    'users' => array('*')  
                ),  
            );  
        }  
}

We set the specific filter in the filters method. We can see that there is an accessControl parameter in the array returned by the filters method. There is a filterAccessControl method in the CController class:
Php code

public function filterAccessControl($filterChain)  
{  
    $filter=new CAccessControlFilter;  
    $filter->setRules($this->accessRules());  
    $filter->filter($filterChain);  
}

Create a new CAccessControlFilter instance inside, and pass in the parameters returned by the accessRules() method when setRules.
$filter->filter($filterChain) Then continue to call other filters.
And all specific authorization rules are defined in accessRules:
Php code

public function accessRules()  
    {  
        return array(  
            array('deny',  
                'actions'=>array('create', 'edit'),  
                'users'=>array('?'),  
            ),  
            array('allow',  
                'actions'=>array('delete'),  
                'roles'=>array('admin'),  
            ),  
            array('deny',  
                'actions'=>array('delete'),  
                'users'=>array('*'),  
            ),  
        );  
    }


For specific rules, please refer to the yii manual .
3. Add a new verification system:
First we inherit a CAdminUser from CWebUser:
Php code

class CAdminWebUser extends CWebUser  
{  
    public $loginUrl = array('admin/admin/login');  
}

We need to It is placed in components
If it is a global application, pass the components section of protected/config/main.php:
Php code

'user'=>array(  
    // enable cookie-based authentication  
        'class' => 'CAdminUser',  
    'allowAutoLogin'=>true,  
       'loginUrl' => array('site/login'),  
),

If it is in modules Then add the following code in the init method of the module class:
Php code

$this->setComponents(array(  
       'adminUser' => array(  
                'class' => 'CAdminWebUser',  
                'allowAutoLogin' => false,  
        )  
));

Final calling method
Php code

//全局应用  
Yii::app()->getComponent('adminUser');  
//在模块中  
Yii::app()->controller->module->getComponent('adminUser');

But This is not enough, we also need to modify the Controller's filter. We need to customize a filter to implement the verification and authorization of another user
The first step is to customize a filter:
Php Code

class CAdminAccessControlFilter extends CAccessControlFilter  
{  
    protected function preFilter($filterChain)  
    {  
        $app=Yii::app();  
        $request=$app->getRequest();  
        $user = Yii::app()->controller->module->getComponent('adminUser');  
        $verb=$request->getRequestType();  
        $ip=$request->getUserHostAddress();  
        foreach($this->getRules() as $rule)  
        {  
            if(($allow=$rule->isUserAllowed($user,$filterChain->controller,$filterChain->action,$ip,$verb))>0) // allowed  
                break;  
            else if($allow<0) // denied  
            {  
                $this->accessDenied($user);  
                return false;  
            }  
        }  
        return true;  
    }  
}

Rewrite the filterAccessController method of the CController class
Php code

public function filterAccessControl($filterChain)  
{  
    $filter = new CAdminAccessControlFilter();  
    $filter->setRules($this->accessRules());  
    $filter->filter($filterChain);  
}  
//在这里我们使用自定义的filter类替换了原来的filter

OK, here we can specify in the accessRules() of this Controller adminUser's authorization

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About the implementation of the login function in the Yii framework of PHP

How to modify yii2.0 users The user table used for login is another table

The above is the detailed content of How to add a new user verification in yii. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn