Yii Framework 2.0 Tutorial

Yii Framework 2.0 User Login From Database

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

//FOR ADVANCED
backend/config/main.php
OR
//FOR BASIC
config/main.php
Add the mysql database credentials in main.php file

<?php
..............
    'modules' => [],
    'components' => [
        'db'=>[
            'class'=>'yii\db\Connection',
            'dsn' => 'mysql:host=localhost;dbname=usermanagementsystem',
            'username' => 'root',
            'password' => '',
            'charset' => 'utf8'            
        ],
        'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => true,
        ],
..............

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

<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "tbl_user".
 *
 * @property string $userid
 * @property string $username
 * @property string $password
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['username', 'password'], 'string', 'max' => 100]            
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'userid' => 'Userid',
            'username' => 'Username',
            'password' => 'Password'
        ];
    }    
}

Impldements namespaces

Add the following namespaces in 'User' model class
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
Implements the IdentityInterface interface class with 'User' model class

class User extends \yii\db\ActiveRecord  implements IdentityInterface

Add Login Process Functions

After created 'User.php' model add the following functions into 'User' model.
    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
        /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
/* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
          return static::findOne(['access_token' => $token]);
    }
 
/* removed
    public static function findIdentityByAccessToken($token)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
*/
    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param  string      $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        $expire = \Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        if ($timestamp + $expire < time()) {
            // token expired
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Security::generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Security::generateRandomKey();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
    /** 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

'user' => [
            'identityClass' => 'app\models\User',
            'enableAutoLogin' => false,
        ],

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

Yii 2.0 User Login

<?php

namespace app\models;

use Yii;
use yii\base\NotSupportedException;
use yii\db\ActiveRecord;
use yii\helpers\Security;
use yii\web\IdentityInterface;
/**
 * This is the model class for table "tbl_user".
 *
 * @property string $userid
 * @property string $username
 * @property string $password
 */
class User extends \yii\db\ActiveRecord  implements IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tbl_user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['username', 'password'], 'required'],
            [['username', 'password'], 'string', 'max' => 100]            
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'userid' => 'Userid',
            'username' => 'Username',
            'password' => 'Password'
        ];
    }    
    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
        /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
/* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
          return static::findOne(['access_token' => $token]);
    }
 
/* removed
    public static function findIdentityByAccessToken($token)
    {
        throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
    }
*/
    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username]);
    }

    /**
     * Finds user by password reset token
     *
     * @param  string      $token password reset token
     * @return static|null
     */
    public static function findByPasswordResetToken($token)
    {
        $expire = \Yii::$app->params['user.passwordResetTokenExpire'];
        $parts = explode('_', $token);
        $timestamp = (int) end($parts);
        if ($timestamp + $expire < time()) {
            // token expired
            return null;
        }

        return static::findOne([
            'password_reset_token' => $token
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    /**
     * Validates password
     *
     * @param  string  $password password to validate
     * @return boolean if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->password === sha1($password);
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Security::generatePasswordHash($password);
    }

    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->auth_key = Security::generateRandomKey();
    }

    /**
     * Generates new password reset token
     */
    public function generatePasswordResetToken()
    {
        $this->password_reset_token = Security::generateRandomKey() . '_' . time();
    }

    /**
     * Removes password reset token
     */
    public function removePasswordResetToken()
    {
        $this->password_reset_token = null;
    }
    /** EXTENSION MOVIE **/

}
  • Sabbir Ahmed

    Great Article
    Working like a charm

  • Luis M

    hi, i have problem error :

    Declaration of appmodelsUser::findIdentityByAccessToken() must be compatible with yiiwebIdentityInterface::findIdentityByAccessToken($token, $type = NULL)

    • Luis M

      edit : appmodelsUser::findIdentityByAccessToken() for appmodelsUser::findIdentityByAccessToken($token, $type = NULL) and add return static::findOne([‘access_token’ => $token]);

      • Shelby

        Did you get this fixed? can you plz explain how you fixed?

        • Luis M

          im edit user.php and change for
          public static function findIdentityByAccessToken($token, $type = null)
          {
          return static::findOne([‘access_token’ => $token]);
          }

          • m bala

            Updated ‘findIdentityByAccessToken()’ function

  • UTEHN PHNU

    i face this error message.
    “Unknown Property – yiibaseUnknownPropertyException

    Getting unknown property: appmodelsUser::auth_key”

    • Nuengnapha Limnuson

      thanks!

      how I get user session I use Yii::$app->user->identit->username it not work.

      • m bala

        use this “Yii::$app->user->identity->username”. You missed ‘y’ in identity

        • Nuengnapha Limnuson

          I mean Yii::$app->user->identity->username ,it not work

  • Luis M

    mmm i have problem im not implement correctly yii2 session any example ?? im access to url and enter to views im not logg.

  • vahid

    wheres “app” in your text you write app/models/User

  • vinotha

    i tried the above coding but i have a error.simply username or password invalid.
    in main.php
    ===========
    [],
    ‘components’ => [
    ‘db’=>[
    ‘class’=>’yiidbConnection’,
    ‘dsn’ => ‘mysql:host=localhost;dbname=fms’,
    ‘username’ => ‘root’,
    ‘password’ => ”,
    ‘charset’ => ‘utf8’
    ],
    ‘user’ => [
    ‘identityClass’ => ‘commonmodelsUser’,
    ‘enableAutoLogin’ => false,
    ],

    ?>
    User.php
    ========
    100]
    ];
    }

    /**
    36 * @inheritdoc
    37 */
    public function attributeLabels()
    {
    return [
    ‘userid’ => ‘Userid’,
    ‘username’ => ‘Username’,
    ‘password’ => ‘Password’
    ];
    }

    /** INCLUDE USER LOGIN VALIDATION FUNCTIONS**/
    /**
    003 * @inheritdoc
    004 */
    public static function findIdentity($id)
    {
    return static::findOne($id);
    }
    /**
    011 * @inheritdoc
    012 */
    /* modified */
    public static function findIdentityByAccessToken($token, $type = null)
    {
    return static::findOne([‘access_token’ => $token]);
    }

    /* removed
    020 public static function findIdentityByAccessToken($token)
    021 {
    022 throw new NotSupportedException(‘”findIdentityByAccessToken” is not implemented.’);
    023 }
    024 */
    /**
    026 * Finds user by username
    027 *
    028 * @param string $username
    029 * @return static|null
    030 */
    public static function findByUsername($username)
    {
    return static::findOne([‘username’ => $username]);
    }

    /**
    037 * Finds user by password reset token
    038 *
    039 * @param string $token password reset token
    040 * @return static|null
    041 */
    public static function findByPasswordResetToken($token)
    {
    $expire = Yii::$app->params[‘user.passwordResetTokenExpire’];
    $parts = explode(‘_’, $token);
    $timestamp = (int) end($parts);
    if ($timestamp + $expire $token
    ]);
    }

    /**
    058 * @inheritdoc
    059 */
    public function getId()
    {
    return $this->getPrimaryKey();
    }

    /**
    066 * @inheritdoc
    067 */
    public function getAuthKey()
    {
    return $this->auth_key;
    }

    /**
    074 * @inheritdoc
    075 */
    public function validateAuthKey($authKey)
    {
    return $this->getAuthKey() === $authKey;
    }

    /**
    082 * Validates password
    083 *
    084 * @param string $password password to validate
    085 * @return boolean if password provided is valid for current user
    086 */
    public function validatePassword($password)
    { return $this->password === sha1($password);
    return Security::validatePassword($password, $this->password_hash);
    }

    /**
    094 * Generates password hash from password and sets it to the model
    095 *
    096 * @param string $password
    097 */
    public function setPassword($password)
    {
    $this->password_hash = Security::generatePasswordHash($password);
    }

    /**
    104 * Generates “remember me” authentication key
    105 */
    public function generateAuthKey()
    {
    $this->auth_key = Security::generateRandomKey(); }

    /**
    112 * Generates new password reset token
    113 */
    public function generatePasswordResetToken()
    {
    $this->password_reset_token = Security::generateRandomKey() . ‘_’ . time();
    }

    /**
    120 * Removes password reset token
    121 */
    public function removePasswordResetToken()
    {
    $this->password_reset_token = null; }
    }

    in my db table is

    userid pk AI
    username varchar100
    password varchar100

    what can i do further.

    please help me.

    thanks in advance

    • mbala

      Hi updated the new code. It is working for me. Please check it. If you get any problem, Please reply me.

  • alexxio

    this doesn’t work for me, i get redirected and i am always guest even if everything seems ok. can you help me providing a working example? thanks

    • m bala

      Add the below code in config/web.php
      ‘user’ => [
      ‘identityClass’ => ‘appmodelsUser’,

      ….

  • Youda

    Not working still takes the User.php on common path and when i replace it with the one i need i got this error : ”
    Cannot redeclare commonmodelsUser::validatePassword()”

    • m bala

      In config/web.php
      ‘user’ => [
      ‘identityClass’ => ‘appmodelsUser’,….

      • Youda

        You mean in config/main-local.php i did this now its throwing invalid username or password

        • Youda

          It’s working thank you, to those who may face this, the problem was validatePassword() function just remove sha1()

          • Gokhan

            Do not rremove sha1(). just do this:

            return trim($this->password) === sha1($password);

          • Grainne Nolan

            This hasn’t worked for me, still throwing invalid username or password. All suggestions welcome. Thanks.

      • Youda

        Now its using the right User.php & Loginform.php but it keeps throwing “Incorrect username or password ” do you have any idea what may cause the problem ??

  • Pddsi4g

    Hello,

    I have a problem when I set enableAutoLogin to false: the login screen is the only one that I see. But if I set it to true, I works perfectly. Any idea ? Any help is welcome.

    Thanks

  • graduategamers

    Thanks, I was skipping the steps at “Assign identityClass” until I got your tutorial.

  • Dipanshu Mahajan

    Can you please upload zip of your working code

  • Dipanshu Mahajan

    How can we signup new user so that we can use login

  • Gustavo

    Can you share de Security helper class implementation?
    Thanks.

  • Lisa Okta

    hello mr.

    after I followed the above article
    i have problem, i can’t login with database and i can’t with admin and demo.

    is there any idea, I have to how or what I need to make changes?

    please help me..
    Thanks

  • how validate login with 2 table, which is table user and table customer?.
    if login as user will redirect to backend, if login as customer will be redirect to frontend.

    What should i do?.

  • john son

    can we use user table having columns like Username,Password (PascalCasing)