Yii2 User Login from Database

By Garima Shrivatasva
4 Comments  

1. Creating Database and Model

Create a User database table with Id, username, password,email and your own requirements . Now go to the Model generator and create a user Model using Gii tool. Model is a PHP class that maps data from a database into PHP objects. Model allows you to fetch, update, select and delete rows from database. In this model you will have to implement the IdentityInterface class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface.IdentityInterface defines several methods and add two additional functions validatePassword() for valid password and findByUsername() for find current user name.


public static function findByUsername($username) {
        return self::findOne(['username' => $username]);
    }
    public function validatePassword($password) {
        return $this->password === $password;      
}

LoginForm class which is saved under app\models\LoginForm. In Login form you will have to define User model so it will return back the userclass


LoginForm extends Model
 { 
public $username; 
public $password; 
public $email; 
public $rememberMe = true;	
}

This is the class where we will connect application with User database table, and make it work with database.


public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::findByUsername($this->username);
        }
        return $this->_user;
    }

findByUsername () search for a user in a database using username.


  • If user with provided username doesn’t exist, then set ERROR_USERNAME_INVALID .
  • If user exists, then check it password. If password doesn’t exist, then set ERROR_PASSWORD_INVALID.
  • If user and user’s password is exists, then save user’s id, name, password and user’s type to the session.

user’s Id should always stored in session never in a cookie.

2. Creating Action

Create a login action in SiteController. Defined new LoginForm object and check if user submitted a login form, then get the values (username, password) and try to validate them.


public function actionLogin() {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }
        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            //return $this->goBack();
        }
        return $this->render('login', [
                    'model' => $model,
        ]);
    }

User is the class for the user application component that manages the user authentication status. You may use $isGuest to determine whether the current user is a guest or not. If the user is a guest, the $identity property would return null. Otherwise, it would be an instance of yii\web\IdentityInterface.


You may call various methods to change the user authentication status:

login(): sets the specified identity and remembers the authentication status in session and cookie;

logout(): marks the user as a guest and clears the relevant information from session and cookie;

setIdentity(): changes the user identity without touching session or cookie.


Comments

Cortar Propecia Digoxin Sales cialis overnight shipping from usa Cialis Rezept Gunstig Kaufen Rayh Health Care Viagra Cost Of Generic Sildenafil
Ellqueelo   30 May 2019   

Discount For Sale Amoxicilina Germany Best Website Free Shipping tadalafil cialis from india Sertraline Online Best Price 25mg Generic Viagra
Ellqueelo   09 May 2019   

Buy Cialis Online No Prescription Ciprofloxacin Generic Baclofene Ou Lioresal propecia espana bueno Cialis 10 Mg Compresse Kamagra Oral Jelly Oder Tabletten Amoxicillin Interaction With Sudafed
Matoscist   26 Apr 2019   

good
garima   15 Aug 2017