The landing mechanism of YII
Yii generation application has provided the most basic user login mechanism. We use YII to generate a new application, into the protected/components directory, we can see the useridentity.php file, inside the Useridentity class has only one public function as follows:
Public function Authenticate ()
{
$users =array (
//username => password
' demo ' => ' demo ',
' Admin ' => ' admin ',
);
if (!isset ($users [$this->username])
$this->errorcode=self::error_username_invalid;
ElseIf ($users [$this->username]!== $this->password)
$this->errorcode=self::error_password_invalid;
else
$this->errorcode=self::error_none;
Return! $this->errorcode;
}
This class in components, will be loaded at the beginning of the application, for the most basic user authentication, you can see that the function at the beginning is simply defined two user demo and admin, and the password is only Demo and admin, if so if your user is very limited, you can directly modify the Add users here, more words we say later. The If else below the function is used to check if the username and password are valid, and to generate error_username_invalid,error_password_invalid these errors when an error occurs. In general, the real user name password verification, and the basic logic processing after landing.
See this class still does not see the login control process. Follow the Model/control/view principle, we can see the landing process in these three aspects of the embodiment. First into the Models folder, you can see a loginform class file, which inherits Cformmodel, and encapsulates the data and business logic of the login for the derived class of the form model. The comparison core functions are as follows:
/** * authenticates the password.
* This is the ' authenticate ' validator as declared in rules (). * * Public Function Authenticate ($attribute, $params) {$this->_identity=new useridentity ($this->username, $this-
>password);
if (! $this->_identity->authenticate ()) $this->adderror (' Password ', ' Username or password error ');
}/** * Logs in the user using the given username and password in the model.
* @return Boolean whether login is successful */Public function login () {if ($this->_identity===null) {
$this->_identity=new useridentity ($this->username, $this->password);
$this->_identity->authenticate (); } if ($this->_identity->errorcode===useridentity::error_none) {$duration = $this->rememberme? 3600*24*3 0:0;
Days Yii::app ()->user->login ($this->_identity, $duration);
return true;
else return false; }
Here the authenticate uses the Useridentity class to authenticate the username password, and the login function provides the login function for YII by detecting whether the user's identity has been set and if the error code is empty. For landing. $duration can set the expiration date for an identity.
to see control again, there is an action in Sitecontroler that is about logging on, that is Actionlogin, the function is as follows:
/** * Displays the login page/Public function Actionlogin () {if (!defined (' C Rypt_blowfish ') | |! crypt_blowfish) throw new Chttpexception ("This application requires" PHP is compiled with BLOWFISH support F
or crypt (). ");
$model =new LoginForm; If it is AJAX validation request if (Isset ($_post[' Ajax ')) && $_post[' ajax ']=== ' Login-form ') {echo C
Activeform::validate ($model);
Yii::app ()->end ();
}//Collect user input data if (Isset ($_post[' loginform ')) {$model->attributes=$_post[' loginform ']; Validate user input and redirect to the previous page if valid if ($model->validate () && $model->
Login ()) $this->redirect (Yii::app ()->user->returnurl);
}//Display the login form $this->render (' login ', array (' model ' => $model)); }
The login action is based on LoginForm to validate the POST's form to log in or render a new login page.
Finally, the view file is the login.php of the site folder, which is what you see in the login interface.
Combing, we can clearly see YII user login Logic processing, when you enter user name password in the login interface, the form will POST data to Site/login action, loign instantiate a loginform form model, and according to the model inside the V alidate function and login function for login detection, validate will validate the form data according to rule rules, where password validation requires authenticate function, and the authenticate and login function validation are base To the useridentity authenticate function. Therefore, if we change the logic of the login, Lgoinform and loginaction can not be modified, directly change the useridentity authenticate function is basically OK.
The above analysis is Yii automatically generated by the user login logic processing code, seems to be very decent, isn't it? But our system generally to support a lot of user access, in the code simply lists the user name and password is obviously irrational, more mature of course, please database to help us manage. Let's say we create an admin table in our database with the following MYSQL statement:
drop table if exists ' admin '; CREATE table ' admin ' (' admin_id ' int unsigned not NULL auto_increment comment ' primary key ', ' username ' varchar () NOT NULL Comment ' login name ', ' PSW ' char (+) NOT null comment ' login password (two times SHA1) ', ' Nick ' varchar () not null comment ' nickname ', ' Add_ti Me ' datetime NOT NULL comment ' creation time ', ' login_time ' datetime null comment ' Recent logon time ', unique key (' username '), Primar
Y key (' admin_id ')) engine=innodb default Charset=utf8 comment= ' admin table ';
Mysql We'll build the admin model with GII, and then we can go back to our original Component useridentity.php rewrite the authenticate function to Implement our own user name password verification. For security reasons, password using two SHA1 encryption, so will collect the password two times SHA1 encryption, and then in the Admin we created to find out if there is a username corresponding to the form input, and then the password than the encryption, if all through after the user's commonly used information by The SetState function is set to the user field for Yii, such as $this->setstate (' Nick ', $user->nick); After this sentence, you can access the nickname of the current login user directly through Yii:app ()->user->nick, instead of querying the database. and $user->login_time = Date (' y-m-d h:i:s '); is to update the user login time and save it to the database with the next sentence.
Public function Authenticate ()
{
if (strlen ($this->password) > 0)
$this->password = SHA1 (SHA1 ($ This->password));
$user = Admin::model ()->findbyattributes (Array (' username ' => $this->username));
if ($user = = null)
$this->errorcode=self::error_username_invalid;
ElseIf (!) ( $user instanceof Admin) | | ($user->psw!= $this->password))
$this->errorcode=self::error_password_invalid;
else
{
$this->setstate (' admin_id ', $user->admin_id);
$this->setstate (' Nick ', $user->nick);
$this->setstate (' username ', $user->username);
$user->login_time = Date (' y-m-d h:i:s ');
$user->save ();
$this->errorcode=self::error_none;
}
Return! $this->errorcode;
}
And if you want to modify the landing interface, then enter the view inside the site folder in the login.php, and toss to make it the way you want, so that our own landing process has been completed. Is it convenient to have Yii ~
Set up automatic login
the principle of automatic login is simple. The main thing is to use cookies to achieve
At the first logon, if the login is successful and the next automatic login is selected, the user's authentication information is saved to the cookie, and the cookie is valid for 1 years or months.
The next time you log in to determine whether the cookie stored in the user's information, if there is a cookie stored in the user information to log in,
Configuring the User Component
First set the user component in the components of the configuration file
' User ' => ['
identityclass ' => ' app\models\user ',
' Enableautologin ' => true,
],
We see Enableautologin is used to determine if you want to enable the Automatic logon feature, which is independent of the next automatic login on the interface.
If Enableautologin is true, if the next automatic logon is selected, the user information is stored in a cookie and the cookie is set to be valid for 3600*24*30 seconds for the next logon
Now let's look at how Yii is implemented.
First log in to save cookies
1, Login login function
Public Function Login ($identity, $duration = 0)
{
if ($this->beforelogin ($identity, False, $duration)) {
$this->switchidentity ($identity, $duration);
$id = $identity->getid ();
$ip = Yii:: $app->getrequest ()->getuserip ();
Yii::info ("User ' $id ' logged in from $ip with duration $duration.", __method__);
$this->afterlogin ($identity, False, $duration);
}
Return! $this->getisguest ();
}
Here is a simple login, then execute the Switchidentity method, set the authentication information.
2, Switchidentity set the authentication information
Public Function switchidentity ($identity, $duration = 0)
{
$session = Yii:: $app->getsession ();
if (! Yii_env_test) {
$session->regenerateid (True);
}
$this->setidentity ($identity);
$session->remove ($this->idparam);
$session->remove ($this->authtimeoutparam);
if ($identity instanceof identityinterface) {
$session->set ($this->idparam, $identity->getid ());
if ($this->authtimeout!== null) {
$session->set ($this->authtimeoutparam, Time () + $this-> authtimeout);
}
if ($duration > 0 && $this->enableautologin) {
$this->sendidentitycookie ($identity, $duration);
}
} ElseIf ($this->enableautologin) {
Yii:: $app->getresponse ()->getcookies ()->remove (New Cookie ($ This->identitycookie));
}
This method is more important and requires this method to be invoked when exiting.
This method has three main functions
Set the duration of a session
If the cookie is valid for more than 0 and is allowed to log on automatically, the user's authentication information is saved to the cookie
If you allow automatic logon, delete cookie information. This is used when the exit is invoked. The $identity passed in is null when exiting
protected function Sendidentitycookie ($identity, $duration)
{
$cookie = new Cookie ($this->identitycookie) ;
$cookie->value = Json_encode ([
$identity->getid (),
$identity->getauthkey (),
$duration,
]);
$cookie->expire = time () + $duration;
Yii:: $app->getresponse ()->getcookies ()->add ($cookie);
}
The user information stored in the cookie contains three values:
- $identity->getid ()
- $identity->getauthkey ()
- $duration
GetId () and Getauthkey () are in the Identityinterface interface. We also know that the user model is required to implement the Identityinterface interface when setting the user component. So, you can get the first two values in the user model, and the third value is the expiration date of the cookie.
Automatic login from Cookie
From the above we know that the user's authentication information has been stored in the cookie, then the next time directly from the cookie to take information and then set it.
1, AccessControl user access control
Yii provides a accesscontrol to determine whether a user is logged in, and this does not need to be judged in every action.
Public function behaviors ()
{return
[
' Access ' => [
' class ' => accesscontrol::classname (),
' only ' => [' logout '],
' rules ' => [
[
' Actions ' => [' logout '],
' Allow ' => true,
' Roles ' => [' @ '],
],
],
],]
;
2, Getisguest, getidentity to determine whether to authenticate users
Isguest is the most important attribute in the automatic logon process.
In the above AccessControl access control through the Isguest attribute to determine whether the user is authenticated, and then in the Getisguest method is called Getidentity to obtain user information, if not empty on the description is authenticated users, otherwise it is tourists (not logged in).
Public Function getisguest ($checkSession = True)
{return
$this->getidentity ($checkSession) = = null;
} Public
function getidentity ($checkSession = True)
{
if ($this->_identity = False) {
if ($checkSession) {
$this->renewauthstatus ();
} else { return
null;
}
}
return $this->_identity;
}
3, renewauthstatus to regenerate user authentication information
protected function Renewauthstatus () {$session = Yii:: $app->getsession (); $id = $session->gethassessionid () | | $session->getisactive ()?
$session->get ($this->idparam): null;
if ($id = = null) {$identity = null;
else {/** @var identityinterface $class/$class = $this->identityclass;
$identity = $class:: findidentity ($id);
$this->setidentity ($identity); if ($this->authtimeout!== null && $identity!== null) {$expire = $session->get ($this->authtimeout
Param);
if ($expire!== null && $expire < time ()) {$this->logout (false);
else {$session->set ($this->authtimeoutparam, Time () + $this->authtimeout);
} if ($this->enableautologin) {if ($this->getisguest ()) {$this->loginbycookie ();
} elseif ($this->autorenewcookie) {$this->renewidentitycookie ();
}
}
}
This section first uses the session to judge the user, because the user already exists in the session after logging in. Then, if you are logged in automatically, log in with cookie information.
4, through the saved cookie information to login Loginbycookie
protected function Loginbycookie () {$name = $this->identitycookie[' name ');
$value = Yii:: $app->getrequest ()->getcookies ()->getvalue ($name);
if ($value!== null) {$data = Json_decode ($value, true);
if (count ($data) = = 3 && isset ($data [0], $data [1], $data [2])) {list ($id, $authKey, $duration) = $data;
/** @var identityinterface $class * * $class = $this->identityclass;
$identity = $class:: findidentity ($id); if ($identity!== null && $identity->validateauthkey ($authKey)) {if ($this->beforelogin ($identity
, true, $duration)) {$this->switchidentity ($identity, $this->autorenewcookie? $duration: 0);
$ip = Yii:: $app->getrequest ()->getuserip ();
Yii::info ("User ' $id ' logged in from $ip via cookie.", __method__);
$this->afterlogin ($identity, True, $duration);
}} elseif ($identity!== null) { Yii::warning ("Invalid Auth key attempted for user ' $id ': $authKey", __method__);
}
}
}
}
The cookie value is read First, then $data = Json_decode ($value, True), and deserialized to an array.
This from the above code can know that in order to implement automatic login, these three values must have a value. In addition, the user model must also implement Findidentity, Validateauthkey these two methods.
Once the login is complete, you can reset the expiration of the cookie so that it works together.
$this->switchidentity ($identity, $this->autorenewcookie $duration: 0);
Third, exit logout
The Public function logout ($destroySession = true) {$identity = $this->getidentity ();
if ($identity!== null && $this->beforelogout ($identity)) {$this->switchidentity (null);
$id = $identity->getid ();
$ip = Yii:: $app->getrequest ()->getuserip ();
Yii::info ("User ' $id ' logged out from $ip.", __method__);
if ($destroySession) {Yii:: $app->getsession ()->destroy ();
$this->afterlogout ($identity);
return $this->getisguest ();
The Public Function switchidentity ($identity, $duration = 0) {$session = Yii:: $app->getsession (); if (!
Yii_env_test) {$session->regenerateid (true);
$this->setidentity ($identity);
$session->remove ($this->idparam);
$session->remove ($this->authtimeoutparam);
if ($identity instanceof identityinterface) {$session->set ($this->idparam, $identity->getid ()); if ($this->authtimeout!==NULL) {$session->set ($this->authtimeoutparam, Time () + $this->authtimeout); } if ($duration > 0 && $this->enableautologin) {$this->sendidentitycookie ($identity, $dura
tion); } elseif ($this->enableautologin) {Yii:: $app->getresponse ()->getcookies ()->remove (New Cookie ($thi
S->identitycookie));
}
}
When exiting, set the current authentication to null before deciding to delete the relevant cookie information if it is an automatic login function.