16

I have been trying to search on the Internet how to write the code in Yii framework 2.0 so that user can login with the credentials stored in the database and not from the array, prefixed in models/User.php. I know how to do that in Yii 1. But in Yii 2.0, I really don't know how to do that. Since Yii 2.0 has not been released yet (only the beta version is available), I could not find many Yii 2.0 tutorials on the Internet about logging-in with the database.

1

2 Answers 2

31

You can implement database user management using extesions like https://github.com/amnah/yii2-user.

OR

If you want to write your own custom script to manage the users you can override Yii2 identityClass.

In the component section of your config add:

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

Please note that your user model MUST IMPLEMENT \yii\web\IdentityInterface

Here is the example of the model class that you can use to implement database authentication

namespace app\models;

//app\models\gii\Users is the model generated using Gii from users table

use app\models\gii\Users as DbUser;

class User extends \yii\base\Object implements \yii\web\IdentityInterface {

public $id;
public $username;
public $password;
public $authKey;
public $accessToken;
public $email;
public $phone_number;
public $user_type;

/**
 * @inheritdoc
 */
public static function findIdentity($id) {
    $dbUser = DbUser::find()
            ->where([
                "id" => $id
            ])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * @inheritdoc
 */
public static function findIdentityByAccessToken($token, $userType = null) {

    $dbUser = DbUser::find()
            ->where(["accessToken" => $token])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

/**
 * Finds user by username
 *
 * @param  string      $username
 * @return static|null
 */
public static function findByUsername($username) {
    $dbUser = DbUser::find()
            ->where([
                "username" => $username
            ])
            ->one();
    if (!count($dbUser)) {
        return null;
    }
    return new static($dbUser);
}

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

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

/**
 * @inheritdoc
 */
public function validateAuthKey($authKey) {
    return $this->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->password === $password;
}

}

I hope that would be helpful to you . Cheers :)

6
  • Works great, thanks! Now we have two model classes, User and gii/Users. Is it possible to use just the default User class only? If yes, how can I implement that? Thanks in advanced!
    – O Connor
    Commented Sep 14, 2014 at 13:49
  • 1
    Yes you can do so by extending yii/db/ActiveRecord instead of \yii\base\Object and replace "DbUser" object in the code above with "self". Also you need to mention the table name for holding the user data using the following method : public static function tableName() { return 'users';// name of the db table } And probably you could add some validation rules if required.
    – Rx Seven
    Commented Sep 14, 2014 at 19:35
  • is authkey and accestoken are mandatory columns in the Users table in the database ? will it effect the custom login in yii2 if these 2 columns will not be ther in the table? Commented Jul 4, 2015 at 11:14
  • I don't think it should affect anything. You should be fine without authkey/aceestoken fields. Cheers !!
    – Rx Seven
    Commented Jul 7, 2015 at 1:43
  • I agree with (and implemented) @RxSeven 's method above.
    – Harry B
    Commented Jul 9, 2015 at 14:51
4

Check the Yii2 advanced application:

https://github.com/yiisoft/yii2-app-advanced

There full implementation of signup, login, resetPassword for Users stored in DB.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.