Search code examples
phpmysqlauthenticationyiiyii2-basic-app

Login Error while trying to login using user from database [Yii2-Basic]


Default on yii2 Basic, user can login using user, user and admin,admin. But, I need the app can access using username and password from my sql database. In my database, I've a table called ùser thath contain username, password, etc. I'm trying to following this suggestion.

But, it give error like this Getting write-only property: app\models\User::password

This is my code:

User.php -> model class

<?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 "user".
 *
 * @property integer $id
 * @property string $username
 * @property string $email
 * @property string $password_hash
 * @property string $auth_key
 */


class User extends \yii\db\ActiveRecord  implements IdentityInterface {

/**
 * @inheritdoc
 */
public static function tableName() {
    return 'user';
}

/**
 * @inheritdoc
 */
public function rules() {
    return [
        [['username', 'email'], 'required'],
        [['username', 'name', 'company'], 'string', 'max' => 100],
        [['email'], 'string', 'max' => 250],
        [['password_hash'], 'string', 'max' => 60],
        [['auth_key'], 'string', 'max' => 32],
    ];
}

/**
 * @inheritdoc
 */
public function attributeLabels() {
    return [
        'id' => 'ID',
        'username' => 'Username',
        'email' => 'Email',
        'password_hash' => 'Password Hash',
        'auth_key' => 'Auth Key',
    ];
}

/** 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;
}

}

SiteController

<?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;

class SiteController extends Controller
{
/**
 * @inheritdoc
 */
public function behaviors()
{
    return [
        'access' => [
            'class' => AccessControl::className(),
            'only' => ['logout'],
            'rules' => [
                [
                    'actions' => ['logout'],
                    'allow' => true,
                    'roles' => ['@'],
                ],
            ],
        ],
        'verbs' => [
            'class' => VerbFilter::className(),
            'actions' => [
                'logout' => ['post'],
            ],
        ],
    ];
}

/**
 * @inheritdoc
 */
public function actions()
{
    return [
        'error' => [
            'class' => 'yii\web\ErrorAction',
        ],
        'captcha' => [
            'class' => 'yii\captcha\CaptchaAction',
            'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
        ],
    ];
}

/**
 * Displays homepage.
 *
 * @return string
 */
public function actionIndex()
{
    return $this->render('index');
}

/**
 * Login action.
 *
 * @return string
 */
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,
    ]);
}

/**
 * Logout action.
 *
 * @return string
 */
public function actionLogout()
{
    Yii::$app->user->logout();

    return $this->goHome();
}

/**
 * Displays contact page.
 *
 * @return string
 */
public function actionContact()
{
    $model = new ContactForm();
    if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
        Yii::$app->session->setFlash('contactFormSubmitted');

        return $this->refresh();
    }
    return $this->render('contact', [
        'model' => $model,
    ]);
}

/**
 * Displays about page.
 *
 * @return string
 */
public function actionAbout()
{
    return $this->render('about');
}
}

LoginForm

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * LoginForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
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->hasErrors()) {
        $user = $this->getUser();

        if (!$user || !$user->validatePassword($this->password)) {
            $this->addError($attribute, 'Incorrect username or password.');
        }
    }
}

/**
 * Logs in a user using the provided username and password.
 * @return bool whether the user is logged in successfully
 */
public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
    }
    return false;
}

/**
 * Finds user by [[username]]
 *
 * @return User|null
 */
public function getUser()
{
    if ($this->_user === false) {
        $this->_user = User::findByUsername($this->username);
    }

    return $this->_user;
}
}

and this is the configuration I've add based on the suggestion

web.php

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

Any one know why I got this error message? and how to fix this so user can login using data in database.

Any help will be appreciated. Thanks


Solution

  • It's because of this method:

    public function validatePassword($password) {
        return $this->password === sha1($password);
    }
    

    What is it? It's absolutely wrong. It should be:

    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }
    

    Edit: And setPassword method should be:

    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }