Add a new user verification method in yii.

Source: Internet
Author: User
This article provides a detailed analysis of the new user authentication method in yii. For more information, see 1. Why do I need to add a new user verification:
Because I want to apply the website background and foreground in the same yii application. however, the front-end also contains a member management center. the two user verifications are completely different, so two different login pages are required to store user information in different cookies or sessions. therefore, you need to add a user authentication in an application.

2. yii user verification:
Before customizing user authentication, we must first understand the authentication and authorization methods of yii.
To verify a user, we need to define a verification class with verification logic. in yii, this class needs to implement the IUserIdentity interface. different classes can implement different verification methods. generally, the user name and password must be verified for website login. yii provides the CUserIdentity class. this class is generally used to verify the user name and password. after inheritance, we need to override the authenticate () method to implement our own Verification Method. the code is as follows:
Php code

The code is as follows:


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 a user logs in, the following code is called:
Php code

The code is as follows:


// Use the provided user name and password to log on to the user
$ 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

The code is as follows:


// Deregister the current user
Yii: app ()-> user-> logout ();
The user is a component of yii. it must be defined in protected/config/main. php.


Php code

The code is as follows:


'User' => array (
// Enable cookie-based authentication
'Allowautologin' => true,
'Loginurl' => array ('site/login '),
),


The class name of user is not specified here, because in yii, the default user is the instance of the CWebUser class.
We have now enabled user login verification and exit. however, users can access all actions no matter whether they log in or not. Therefore, we need to authorize users to access these actions. in yii, Access Control Filter is used to implement user authorization. let's take a look at a simple Controller with access control:
Php code

The code is as follows:


Class admindefacontroller controller extends CController
{
Public function filters ()
{
Return array ('accesscontrol ');
}
Public function accessRules ()
{
Return array (
Array (
'Allow ',
'Users' => array ('@'),
),
Array (
'Deny ',
'Users' => array ('*')
),
);
}
}


We set a specific filter in the filters method. we can see that the array returned by the filters method contains the accessControl parameter, The CController class has a filterAccessControl method:
Php code

The code is as follows:


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


A CAccessControlFilter instance is created, and the parameters returned by the accessRules () method are passed in during setRules.
$ Filter-> filter ($ filterChain) continues to call other filters.
All specific authorization rules are defined in accessRules:
Php code

The code is as follows:


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, see the yii manual.
3. new verification system:
First, we inherit a CAdminUser from CWebUser:
Php code

The code is as follows:


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


We need to place it in components.
For a global application, use the components section of protected/config/main. php:
Php code

The code is as follows:


'User' => array (
// Enable cookie-based authentication
'Class' => 'cadminuser ',
'Allowautologin' => true,
'Loginurl' => array ('site/login '),
),


In modules, add the following code to the init method of the module class:
Php code

The code is as follows:


$ This-> setComponents (array (
'Adminuser' => array (
'Class' => 'cadminwebuser ',
'Allowautologin' => false,
)
));


Last Call method
Php code

The code is as follows:


// Global Application
Yii: app ()-> getComponent ('adminuser ');
// In the module
Yii: app ()-> controller-> module-> getComponent ('adminuser ');


However, this is not enough. we also need to modify the filter of the Controller. we need to customize a filter to verify and authorize another user.
Step 1: Customize a filter:
Php code

The code is as follows:


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;
}
}


Then rewrite the filterAccessController method of the CController class.
Php code

The code is as follows:


Public function filterAccessControl ($ filterChain)
{
$ Filter = new CAdminAccessControlFilter ();
$ Filter-> setRules ($ this-> accessRules ());
$ Filter-> filter ($ filterChain );
}
// Here we use the custom filter class to replace the original filter


OK. Now we can specify the adminUser authorization in the accessRules () of the Controller.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.