Yii 2.0 User Login From Database

来源:互联网 发布:模拟整容软件 编辑:程序博客网 时间:2024/06/14 17:09
  1. Config The Database
  2. Add LoginForm.php Into Backend/Model
  3. Create User Model
  4. Impldements namespaces
  5. Add Login Process Functions
  6. Assign identityClass
  7. Change namespace in SiteController

Before start the application login steps, We must have to install the application. Use the“Installing Yii2.0″ tutorials to learn about “how to install the yii 2.0 advanced and basic templates application”.

Config The Database

Open the main.php under the following folder structure

1//FOR ADVANCED
2backend/config/main.php
3OR
4//FOR BASIC
5config/main.php

Add the mysql database credentials in main.php file

01<?php
02..............
03    'modules'=> [],
04    'components'=> [
05        'db'=>[
06            'class'=>'yii\db\Connection',
07            'dsn'=> 'mysql:host=localhost;dbname=usermanagementsystem',
08            'username'=> 'root',
09            'password'=> '',
10            'charset'=> 'utf8'           
11        ],
12        'user'=> [
13            'identityClass'=> 'app\models\User',
14            'enableAutoLogin'=> true,
15        ],
16..............

Add LoginForm.php Into Backend/Model

  • Copy the login form file from “common/models/LoginForm.php” into“backend/models/LoginForm.php”
  • Open “backend/models/LoginForm.php” file and change the namespace details from“namespace common\models;” to namespace app\models; on top of the file.

Create User Model

Create the user model using “Yii code generator”
backend/models/User.php

01<?php
02 
03namespace app\models;
04 
05use Yii;
06 
07/**
08 * This is the model class for table "tbl_user".
09 *
10 * @property string $userid
11 * @property string $username
12 * @property string $password
13 */
14class User extends \yii\db\ActiveRecord
15{
16    /**
17     * @inheritdoc
18     */
19    publicstatic function tableName()
20    {
21        return'tbl_user';
22    }
23 
24    /**
25     * @inheritdoc
26     */
27    publicfunction rules()
28    {
29        return[
30            [['username','password'], 'required'],
31            [['username','password'], 'string','max' => 100]           
32        ];
33    }
34 
35    /**
36     * @inheritdoc
37     */
38    publicfunction attributeLabels()
39    {
40        return[
41            'userid'=> 'Userid',
42            'username'=> 'Username',
43            'password'=> 'Password'
44        ];
45    }   
46}

Impldements namespaces

Add the following namespaces in ‘User’ model class

1use yii\base\NotSupportedException;
2use yii\db\ActiveRecord;
3use yii\helpers\Security;
4use yii\web\IdentityInterface;

Implements the IdentityInterface interface class with ‘User’ model class

1class User extends \yii\db\ActiveRecord  implements IdentityInterface

Add Login Process Functions

After created ‘User.php’ model add the following functions into ‘User’ model.

001    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
002        /**
003     * @inheritdoc
004     */
005    publicstatic function findIdentity($id)
006    {
007        returnstatic::findOne($id);
008    }
009 
010    /**
011     * @inheritdoc
012     */
013/* modified */
014    publicstatic function findIdentityByAccessToken($token,$type = null)
015    {
016          returnstatic::findOne(['access_token'=> $token]);
017    }
018  
019/* removed
020    public static function findIdentityByAccessToken($token)
021    {
022        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
023    }
024*/
025    /**
026     * Finds user by username
027     *
028     * @param  string      $username
029     * @return static|null
030     */
031    publicstatic function findByUsername($username)
032    {
033        returnstatic::findOne(['username'=> $username]);
034    }
035 
036    /**
037     * Finds user by password reset token
038     *
039     * @param  string      $token password reset token
040     * @return static|null
041     */
042    publicstatic function findByPasswordResetToken($token)
043    {
044        $expire= \Yii::$app->params['user.passwordResetTokenExpire'];
045        $parts= explode('_',$token);
046        $timestamp= (int) end($parts);
047        if($timestamp + $expire < time()) {
048            // token expired
049            returnnull;
050        }
051 
052        returnstatic::findOne([
053            'password_reset_token'=> $token
054        ]);
055    }
056 
057    /**
058     * @inheritdoc
059     */
060    publicfunction getId()
061    {
062        return$this->getPrimaryKey();
063    }
064 
065    /**
066     * @inheritdoc
067     */
068    publicfunction getAuthKey()
069    {
070        return$this->auth_key;
071    }
072 
073    /**
074     * @inheritdoc
075     */
076    publicfunction validateAuthKey($authKey)
077    {
078        return$this->getAuthKey() === $authKey;
079    }
080 
081    /**
082     * Validates password
083     *
084     * @param  string  $password password to validate
085     * @return boolean if password provided is valid for current user
086     */
087    publicfunction validatePassword($password)
088    {
089        return$this->password === sha1($password);
090    }
091 
092    /**
093     * Generates password hash from password and sets it to the model
094     *
095     * @param string $password
096     */
097    publicfunction setPassword($password)
098    {
099        $this->password_hash = Security::generatePasswordHash($password);
100    }
101 
102    /**
103     * Generates "remember me" authentication key
104     */
105    publicfunction generateAuthKey()
106    {
107        $this->auth_key = Security::generateRandomKey();
108    }
109 
110    /**
111     * Generates new password reset token
112     */
113    publicfunction generatePasswordResetToken()
114    {
115        $this->password_reset_token = Security::generateRandomKey() .'_' . time();
116    }
117 
118    /**
119     * Removes password reset token
120     */
121    publicfunction removePasswordResetToken()
122    {
123        $this->password_reset_token = null;
124    }
125    /** EXTENSION MOVIE **/

Assign identityClass

Default identityClass is “common\models\User”(for advanced application). Now we configured new identityClass class in“app\models\User” and change it in “backend\config\main.php” file. ChangeenableAutoLogin value to false

1'user' => [
2            'identityClass'=> 'app\models\User',
3            'enableAutoLogin'=> false,
4        ],

Change namespace in SiteController

The login functions are available in ‘SiteController.php’ and we have to change ‘LoginForm’ namespace. Find the“use common\models\LoginForm;” and replace the “use app\models\LoginForm;”
Now you can login from database ‘user’ table for yii 2.0 applicatons.

User.php Model


001<?php
002 
003namespace app\models;
004 
005use Yii;
006use yii\base\NotSupportedException;
007use yii\db\ActiveRecord;
008use yii\helpers\Security;
009use yii\web\IdentityInterface;
010/**
011 * This is the model class for table "tbl_user".
012 *
013 * @property string $userid
014 * @property string $username
015 * @property string $password
016 */
017class User extends \yii\db\ActiveRecord  implements IdentityInterface
018{
019    /**
020     * @inheritdoc
021     */
022    publicstatic function tableName()
023    {
024        return'tbl_user';
025    }
026 
027    /**
028     * @inheritdoc
029     */
030    publicfunction rules()
031    {
032        return[
033            [['username','password'], 'required'],
034            [['username','password'], 'string','max' => 100]           
035        ];
036    }
037 
038    /**
039     * @inheritdoc
040     */
041    publicfunction attributeLabels()
042    {
043        return[
044            'userid'=> 'Userid',
045            'username'=> 'Username',
046            'password'=> 'Password'
047        ];
048    }   
049    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
050        /**
051     * @inheritdoc
052     */
053    publicstatic function findIdentity($id)
054    {
055        returnstatic::findOne($id);
056    }
057 
058    /**
059     * @inheritdoc
060     */
061/* modified */
062    publicstatic function findIdentityByAccessToken($token,$type = null)
063    {
064          returnstatic::findOne(['access_token'=> $token]);
065    }
066  
067/* removed
068    public static function findIdentityByAccessToken($token)
069    {
070        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
071    }
072*/
073    /**
074     * Finds user by username
075     *
076     * @param  string      $username
077     * @return static|null
078     */
079    publicstatic function findByUsername($username)
080    {
081        returnstatic::findOne(['username'=> $username]);
082    }
083 
084    /**
085     * Finds user by password reset token
086     *
087     * @param  string      $token password reset token
088     * @return static|null
089     */
090    publicstatic function findByPasswordResetToken($token)
091    {
092        $expire= \Yii::$app->params['user.passwordResetTokenExpire'];
093        $parts= explode('_',$token);
094        $timestamp= (int) end($parts);
095        if($timestamp + $expire < time()) {
096            // token expired
097            returnnull;
098        }
099 
100        returnstatic::findOne([
101            'password_reset_token'=> $token
102        ]);
103    }
104 
105    /**
106     * @inheritdoc
107     */
108    publicfunction getId()
109    {
110        return$this->getPrimaryKey();
111    }
112 
113    /**
114     * @inheritdoc
115     */
116    publicfunction getAuthKey()
117    {
118        return$this->auth_key;
119    }
120 
121    /**
122     * @inheritdoc
123     */
124    publicfunction validateAuthKey($authKey)
125    {
126        return$this->getAuthKey() === $authKey;
127    }
128 
129    /**
130     * Validates password
131     *
132     * @param  string  $password password to validate
133     * @return boolean if password provided is valid for current user
134     */
135    publicfunction validatePassword($password)
136    {
137        return$this->password === sha1($password);
138    }
139 
140    /**
141     * Generates password hash from password and sets it to the model
142     *
143     * @param string $password
144     */
145    publicfunction setPassword($password)
146    {
147        $this->password_hash = Security::generatePasswordHash($password);
148    }
149 
150    /**
151     * Generates "remember me" authentication key
152     */
153    publicfunction generateAuthKey()
154    {
155        $this->auth_key = Security::generateRandomKey();
156    }
157 
158    /**
159     * Generates new password reset token
160     */
161    publicfunction generatePasswordResetToken()
162    {
163        $this->password_reset_token = Security::generateRandomKey() .'_' . time();
164    }
165 
166    /**
167     * Removes password reset token
168     */
169    publicfunction removePasswordResetToken()
170    {
171        $this->password_reset_token = null;
172    }
173    /** EXTENSION MOVIE **/
174 
175

}


0 0