Home Backend Development PHP Tutorial How to add a new user verification in yii

How to add a new user verification in yii

Jun 15, 2018 pm 04:20 PM
yii User Authentication

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;  
    }  
}
Copy after login

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;
Copy after login


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

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

Php code

'user'=>array(  
    // enable cookie-based authentication  
    'allowAutoLogin'=>true,  
        'loginUrl' => array('site/login'),  
),
Copy after 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('*')  
                ),  
            );  
        }  
}
Copy after login

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);  
}
Copy after login

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('*'),  
            ),  
        );  
    }
Copy after login


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');  
}
Copy after 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'),  
),
Copy after 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,  
        )  
));
Copy after login

Final calling method
Php code

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

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;  
    }  
}
Copy after login

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
Copy after login

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP framework Yii to develop a highly available cloud backup system How to use PHP framework Yii to develop a highly available cloud backup system Jun 27, 2023 am 09:04 AM

With the continuous development of cloud computing technology, data backup has become something that every enterprise must do. In this context, it is particularly important to develop a highly available cloud backup system. The PHP framework Yii is a powerful framework that can help developers quickly build high-performance web applications. The following will introduce how to use the Yii framework to develop a highly available cloud backup system. Designing the database model In the Yii framework, the database model is a very important part. Because the data backup system requires a lot of tables and relationships

Symfony vs Yii2: Which framework is better for developing large-scale web applications? Symfony vs Yii2: Which framework is better for developing large-scale web applications? Jun 19, 2023 am 10:57 AM

As the demand for web applications continues to grow, developers have more and more choices in choosing development frameworks. Symfony and Yii2 are two popular PHP frameworks. They both have powerful functions and performance, but when faced with the need to develop large-scale web applications, which framework is more suitable? Next we will conduct a comparative analysis of Symphony and Yii2 to help you make a better choice. Basic Overview Symphony is an open source web application framework written in PHP and is built on

Data query in Yii framework: access data efficiently Data query in Yii framework: access data efficiently Jun 21, 2023 am 11:22 AM

The Yii framework is an open source PHP Web application framework that provides numerous tools and components to simplify the process of Web application development, of which data query is one of the important components. In the Yii framework, we can use SQL-like syntax to access the database to query and manipulate data efficiently. The query builder of the Yii framework mainly includes the following types: ActiveRecord query, QueryBuilder query, command query and original SQL query

How to use Yii3 framework in php? How to use Yii3 framework in php? May 31, 2023 pm 10:42 PM

As the Internet continues to develop, the demand for web application development is also getting higher and higher. For developers, developing applications requires a stable, efficient, and powerful framework, which can improve development efficiency. Yii is a leading high-performance PHP framework that provides rich features and good performance. Yii3 is the next generation version of the Yii framework, which further optimizes performance and code quality based on Yii2. In this article, we will introduce how to use Yii3 framework to develop PHP applications.

How to cancel win11 login account How to cancel win11 login account Jan 11, 2024 pm 05:24 PM

In the win11 system, we need to log in every time we enter the system. However, if there is only one account in our system or there is no need to protect the account, we do not need to log in every time. At this time, we can cancel the login account by canceling the password. , let’s take a look at the specific methods below. How to cancel the login account in win11 1. First, click the arrow button in the center of the taskbar and quickly select the "Start" option. 2. Next, enter the system settings interface and quickly click the "Run" option to start. 3. Next, enter the command: controluserpasswords2 and press the Enter key. 4. Click to open the "User Account Properties" option and uncheck "To use this machine, users must enter

Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Yii2 vs Phalcon: Which framework is better for developing graphics rendering applications? Jun 19, 2023 am 08:09 AM

In the current information age, big data, artificial intelligence, cloud computing and other technologies have become the focus of major enterprises. Among these technologies, graphics card rendering technology, as a high-performance graphics processing technology, has received more and more attention. Graphics card rendering technology is widely used in game development, film and television special effects, engineering modeling and other fields. For developers, choosing a framework that suits their projects is a very important decision. Among current languages, PHP is a very dynamic language. Some excellent PHP frameworks such as Yii2, Ph

How to set a power-on password on win11 How to set a power-on password on win11 Dec 22, 2023 pm 01:18 PM

If we want to set privacy for our computer, we can set a power-on password for the computer, and it is very convenient. It only needs to be done in the settings. Let’s take a look. How to set a power-on password in win11: 1. First, right-click the "Start" menu and click Settings. 2. Then click "Account". 3. Then click "Login Options". 4. Then find "Password" and click Add. 5. Finally, it can be added successfully.

How to perform user input validation and security filtering in PHP? How to perform user input validation and security filtering in PHP? Jun 29, 2023 pm 03:01 PM

How to perform user input validation and security filtering in PHP? When developing web applications, user input validation and security filtering are very important aspects. If user input is not handled correctly, it can lead to various security vulnerabilities, such as cross-site scripting (XSS) and SQL injection attacks. Therefore, validating and security filtering user input is one of the important measures to protect web applications. This article will introduce how to perform user input validation and security filtering in PHP. Data type validation Before receiving user input, it first needs to be validated

See all articles