title: Yii2 step-by-step guide on login from table in MySQL
body: <p>I'm begining to make the first steps in Yii2. So far, I was able to write an application and connect a table in a database to it, just like I learned to do in Yii1.</p>
  
  <p>The table is <code>contacts</code> and the form in my create view sends the data to the database with no problems.</p>
  
  <p>The problem is that I only can login using Admin/Admin or demo/demo in the static user model that comes built-in in Yii2.</p>
  
  <p>In Yii1.xx i manage to validate login from a table in database using COMPONENTS/useridentity, just like this (I used a table named <code>utilizador</code>, with fields <code>id</code>, <code>utilizador</code> and <code>password</code>):</p>
  
  <pre><code>class UserIdentity extends CUserIdentity
  {
  
      public function authenticate() {
         $conexao=Yii::app()-&gt;db;
         $consulta="select utilizador,password from utilizador ";
         $consulta.="where utilizador='".$this-&gt;username."' and ";
         $consulta.="password='".$this-&gt;password."'";
  
         $resultado=$conexao-&gt;createCommand($consulta)-&gt;query();
  
         $resultado-&gt;bindColumn(1,$this-&gt;username);
         $resultado-&gt;bindColumn(2,$this-&gt;password);
  
         while($resultado-&gt;read()!==false){
          $this-&gt;errorCode=self::ERROR_NONE;
          return !$this-&gt;errorCode;
         }
     }
  
  }
  </code></pre>
  
  <p>With Yii2 I have read a lot of tutorials, including one in Stack Overflow but none of them enlighten me on the procedure to login users with username and password from a MySQL database. Yii2 don't have components/useridentity.php and I don't know where to start and what is the proper code to make it work overriding the static user model that comes out of the box.</p>
  
  <p>I also have tried an extension Yii2-user, read the PDF guide but didn't understand how to call the route's from the vendor folder in my controllers. Made several tries but all failed.</p>
  
  <p>Can someone teach me how to validate login from database in Yii2, preferentially without using an extension?</p>
  
  <p><strong>Edit</strong></p>
  
  <p><strong>I read this tutorial in Stack Overflow</strong>
  <a href="https://stackoverflow.com/questions/25790543/yii-framework-2-0-login-with-user-database">Yii Framework 2.0 Login With User Database</a></p>
  
  <p><strong>And also studied the PDF from Yii2-user extension</strong>, but don't know what to do with following part and next ones of the pdf. It speaks about routes, but i don't know how to work with them:</p>
  
  <p>2.3.1 Show users
  Route /user/admin/index shows a list of registered users. You will be able to see a lot of useful information such as registration time and ip address, confirmation and block status, etc.</p>
  
  <p><strong>I have also read this:</strong>
  <a href="http://www.yiiframework.com/doc-2.0/yii-web-user.html" rel="nofollow noreferrer">http://www.yiiframework.com/doc-2.0/yii-web-user.html</a>
  but I don't think it has the steps to resolve my problem.</p>
  
  <p><strong>EDIT 2</strong></p>
  
  <p>I tried to implement the User Model and LoginForm Model in Yii basic template to validate user logins. Created a database and coneected to it. The database as a table user and fields username, password, authKey, acessToken populated with values. Extended the User Model from ActiveRecord and implemented \yii\web\IdentityInterface in order to make the in-built Yii2 functions do their job. Also wrrited the method <strong>public static function tableName() { return 'user'; }</strong></p>
  
  <p>Every time i try to login it throws -> username or password incorrect, from the validatepassword() in LoginForm Model.</p>
  
  <p><strong>Here is my code:
  LoginForm Model:</strong></p>
  
  <p>
  
  <pre><code>namespace app\models;
  
  use Yii;
  use yii\base\Model;
  
  /**
   * LoginForm is the model behind the login form.
   */
  class LoginForm extends Model
  {
  public $username;
  public $password;
  public $rememberMe = true;
  
  private $_user = false;
  
  /**
   * @return array the validation rules.
   */
  public function rules()
  {
      return [
          // username and password are both required
          [['username', 'password'], 'required'],
          // rememberMe must be a boolean value
          ['rememberMe', 'boolean'],
          // password is validated by validatePassword()
          ['password', 'validatePassword'],
      ];
  }
  
  /**
   * Validates the password.
   * This method serves as the inline validation for password.
   *
   * @param string $attribute the attribute currently being validated
   * @param array $params the additional name-value pairs given in the rule
   */
  public function validatePassword($attribute, $params)
  {
      if (!$this-&gt;hasErrors()) {
          $user = $this-&gt;getUser();
  
          if (!$user || !$user-&gt;validatePassword($this-&gt;password)) {
              $this-&gt;addError($attribute, 'Incorrect username or password.');
          }
      }
  }
  
  /**
   * Logs in a user using the provided username and password.
   * @return boolean whether the user is logged in successfully
   */
  public function login()
  {
      if ($this-&gt;validate()) {
          return Yii::$app-&gt;user-&gt;login($this-&gt;getUser(), $this-&gt;rememberMe ? 3600*24*30 : 0);
      } else {
          return false;
      }
  }
  
  /**
   * Finds user by [[username]]
   *
   * @return User|null
   */
  public function getUser()
  {
      if ($this-&gt;_user === false) {
          $this-&gt;_user = User::findByUsername($this-&gt;username);
      }
  
      return $this-&gt;_user;
  }
  </code></pre>
  
  <p>}</p>
  
  <p><strong>... and here is my User.php Model</strong></p>
  
  <pre><code>&lt;?php
  
  namespace app\models;
  
  use yii\db\ActiveRecord;
  
  class User extends ActiveRecord implements \yii\web\IdentityInterface
  {
  public $id;
  public $username;
  public $password;
  public $authKey;
  public $accessToken;
  
  public static function tableName() { return 'user'; }
  
     /**
   * @inheritdoc
   */
  public static function findIdentity($id) {
      $user = self::find()
              -&gt;where([
                  "id" =&gt; $id
              ])
              -&gt;one();
      if (!count($user)) {
          return null;
      }
      return new static($user);
  }
  
  /**
   * @inheritdoc
   */
  public static function findIdentityByAccessToken($token, $userType = null) {
  
      $user = self::find()
              -&gt;where(["accessToken" =&gt; $token])
              -&gt;one();
      if (!count($user)) {
          return null;
      }
      return new static($user);
  }
  
  /**
   * Finds user by username
   *
   * @param  string      $username
   * @return static|null
   */
  public static function findByUsername($username) {
      $user = self::find()
              -&gt;where([
                  "username" =&gt; $username
              ])
              -&gt;one();
      if (!count($user)) {
          return null;
      }
      return new static($user);
  }
  
  /**
   * @inheritdoc
   */
  public function getId() {
      return $this-&gt;id;
  }
  
  /**
   * @inheritdoc
   */
  public function getAuthKey() {
      return $this-&gt;authKey;
  }
  
  /**
   * @inheritdoc
   */
  public function validateAuthKey($authKey) {
      return $this-&gt;authKey === $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-&gt;password === $password;
  }
  
  }
  </code></pre>
  
  <p><strong>Any ideas ?? -> Thanks...</strong></p>
  
  <p><strong>I don't know what else should i do, perhaps it has a problem in validating the password or find the username, in Yii2 debug it shows that is proper connected to the mysql database.</strong></p>
  
  <p><strong>Don't touched in the siteController actionLogin() because it is equal to the advanced template and i think it is better to stay that way.</strong></p>
  
  <p><strong>EDIT 3 -> 4 HOURS messing with the models code, putting in pratice every solution i read and it still throws "Incorrect username or password." from:</strong></p>
  
  <pre><code>public function validatePassword($attribute, $params)
  {
      if (!$this-&gt;hasErrors()) {
          $user = $this-&gt;getUser();
  
          if (!$user || !$user-&gt;validatePassword($this-&gt;password)) {
              $this-&gt;addError($attribute, 'Incorrect username or password.');
          }
      }
  }
  </code></pre>
  
  <p><strong>I don't want to give up, but i'm considering go back to the old Yii1.xx. There i could easily query the database and make a good login system working.</strong></p>