title: Yii2 Basic template - How to login from mysql database
body: <p>I tried to implement the User Model and LoginForm Model in Yii basic template to validate user logins. I created a database and connected to it. The database as a table user and fields called username, password, authKey, and 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 written this method:</p>
  
  <pre><code>public static function tableName() { return 'user'; }
  </code></pre>
  
  <p>Every time I try to login it throws -> username or password incorrect, from the <code>validatepassword()</code> in LoginForm Model.</p>
  
  <p><strong>Here is my code:</strong></p>
  
  <p>LoginForm Model:</p>
  
  <pre><code>&lt;?php
  
  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>…and here is my User.php Model:</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>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.</p>
  
  <p>Don't messed with the siteController <code>actionLogin()</code> because it is equal to the advanced template and i think it correct to stay that way.</p>
  
  <p>In short, the below function keeps throwing "Incorrect username or password.":</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>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.</p>
  
  <p>I spent almost 72 hours with this login problem and no solution solved it for the basic Yii2 template.</p>
  
  <p>I don't want to use static <code>$users</code> that came as default in the package.</p>
  
  <p><strong>EDIT 2</strong><br>
  <strong>siteController.php</strong></p>
  
  <pre><code>&lt;?php
  
  namespace app\controllers;
  
  use Yii;
  use yii\filters\AccessControl;
  use yii\web\Controller;
  use yii\filters\VerbFilter;
  use app\models\LoginForm;
  use app\models\ContactForm;
  use yii\helpers\url;
  
  class SiteController extends Controller
  {
      public function behaviors()
      {
          return [
              'access' =&gt; [
                  'class' =&gt; AccessControl::className(),
                  'only' =&gt; ['logout'],
                  'rules' =&gt; [
                      [
                          'actions' =&gt; ['logout'],
                          'allow' =&gt; true,
                          'roles' =&gt; ['@'],
                      ],
                  ],
              ],
              'verbs' =&gt; [
                  'class' =&gt; VerbFilter::className(),
                  'actions' =&gt; [
                      'logout' =&gt; ['post'],
                  ],
              ],
          ];
      }
  
      public function actions()
      {
          return [
              'error' =&gt; [
                  'class' =&gt; 'yii\web\ErrorAction',
              ],
              'captcha' =&gt; [
                  'class' =&gt; 'yii\captcha\CaptchaAction',
                  'fixedVerifyCode' =&gt; YII_ENV_TEST ? 'testme' : null,
              ],
          ];
      }
  
      public function actionIndex()
      {
          return $this-&gt;render('index');
      }
  
      public function actionLogin()
      {
          if (!\Yii::$app-&gt;user-&gt;isGuest) {
              return $this-&gt;goHome();
          }
  
          $model = new LoginForm();
          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;login()) {
              return $this-&gt;redirect(Url::toRoute(['contacto/index'])); 
          } else {
              return $this-&gt;render('login', [
                  'model' =&gt; $model,
              ]);
          }
      }
  
      public function actionLogout()
      {
          Yii::$app-&gt;user-&gt;logout();
  
          return $this-&gt;goHome();
      }
  
      public function actionContact()
      {
          $model = new ContactForm();
          if ($model-&gt;load(Yii::$app-&gt;request-&gt;post()) &amp;&amp; $model-&gt;contact(Yii::$app-&gt;params['adminEmail'])) {
              Yii::$app-&gt;session-&gt;setFlash('contactFormSubmitted');
  
              return $this-&gt;refresh();
          } else {
  
                  return $this-&gt;redirect(Url::toRoute(['contacto/create2']));
          }
      }
  
      public function actionAbout()
      {
          return $this-&gt;render('about');
      }
  
      public function actionSkills()
      {
          return $this-&gt;render('skills');
      }
  
      public function actionPortfolio()
      {
          return $this-&gt;render('portfolio');
      }
  
      // tradução do site
      public function beforeAction($action) {
          if (Yii::$app-&gt;session-&gt;has('lang')) {
              Yii::$app-&gt;language = Yii::$app-&gt;session-&gt;get('lang');
          } else {
              Yii::$app-&gt;language = 'us';
          }
          return parent::beforeAction($action);
      }
  
      public function actionLangus(){  
          Yii::$app-&gt;session-&gt;set('lang', 'us'); //or $_GET['lang']
          return $this-&gt;redirect(Url::toRoute(['site/index']));   
      }
  
      public function actionLangpt(){  
          Yii::$app-&gt;session-&gt;set('lang', 'pt'); //or $_GET['lang']
          return $this-&gt;redirect(Url::toRoute(['site/index']));
      }
  }
  </code></pre>