Yii 2.0 User Login From Database

本文深入探讨了前端开发领域的HTML、CSS、JavaScript等核心技术,并着重介绍了AI音视频处理技术在实际应用中的关键概念与实现方法。

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    public static function tableName()
20    {
21        return 'tbl_user';
22    }
23 
24    /**
25     * @inheritdoc
26     */
27    public function rules()
28    {
29        return [
30            [['username', 'password'], 'required'],
31            [['username', 'password'], 'string', 'max' => 100]           
32        ];
33    }
34 
35    /**
36     * @inheritdoc
37     */
38    public function 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    public static function findIdentity($id)
006    {
007        return static::findOne($id);
008    }
009 
010    /**
011     * @inheritdoc
012     */
013/* modified */
014    public static function findIdentityByAccessToken($token, $type = null)
015    {
016          return static::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    public static function findByUsername($username)
032    {
033        return static::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    public static 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            return null;
050        }
051 
052        return static::findOne([
053            'password_reset_token' => $token
054        ]);
055    }
056 
057    /**
058     * @inheritdoc
059     */
060    public function getId()
061    {
062        return $this->getPrimaryKey();
063    }
064 
065    /**
066     * @inheritdoc
067     */
068    public function getAuthKey()
069    {
070        return $this->auth_key;
071    }
072 
073    /**
074     * @inheritdoc
075     */
076    public function 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    public function 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    public function setPassword($password)
098    {
099        $this->password_hash = Security::generatePasswordHash($password);
100    }
101 
102    /**
103     * Generates "remember me" authentication key
104     */
105    public function generateAuthKey()
106    {
107        $this->auth_key = Security::generateRandomKey();
108    }
109 
110    /**
111     * Generates new password reset token
112     */
113    public function generatePasswordResetToken()
114    {
115        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
116    }
117 
118    /**
119     * Removes password reset token
120     */
121    public function 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. Change enableAutoLogin 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    public static function tableName()
023    {
024        return 'tbl_user';
025    }
026 
027    /**
028     * @inheritdoc
029     */
030    public function rules()
031    {
032        return [
033            [['username', 'password'], 'required'],
034            [['username', 'password'], 'string', 'max' => 100]           
035        ];
036    }
037 
038    /**
039     * @inheritdoc
040     */
041    public function 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    public static function findIdentity($id)
054    {
055        return static::findOne($id);
056    }
057 
058    /**
059     * @inheritdoc
060     */
061/* modified */
062    public static function findIdentityByAccessToken($token, $type = null)
063    {
064          return static::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    public static function findByUsername($username)
080    {
081        return static::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    public static 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            return null;
098        }
099 
100        return static::findOne([
101            'password_reset_token' => $token
102        ]);
103    }
104 
105    /**
106     * @inheritdoc
107     */
108    public function getId()
109    {
110        return $this->getPrimaryKey();
111    }
112 
113    /**
114     * @inheritdoc
115     */
116    public function getAuthKey()
117    {
118        return $this->auth_key;
119    }
120 
121    /**
122     * @inheritdoc
123     */
124    public function 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    public function 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    public function setPassword($password)
146    {
147        $this->password_hash = Security::generatePasswordHash($password);
148    }
149 
150    /**
151     * Generates "remember me" authentication key
152     */
153    public function generateAuthKey()
154    {
155        $this->auth_key = Security::generateRandomKey();
156    }
157 
158    /**
159     * Generates new password reset token
160     */
161    public function generatePasswordResetToken()
162    {
163        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
164    }
165 
166    /**
167     * Removes password reset token
168     */
169    public function removePasswordResetToken()
170    {
171        $this->password_reset_token = null;
172    }
173    /** EXTENSION MOVIE **/
174 
175

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值