简体   繁体   中英

How to login Yii2 without database?

I need a help!

I have a working mechanism login with DB but sometimes i need get login process without DB (fake user use).

Static method in User model

public static function findByRoot()
{
   $arr = [
      'id' => 100,
      'created_at' => 1444322024,
      'updated_at' => 1444322024,
      'username' => 'vasya',
      'auth_key' => 'aagsdghfgukfyrtweri',
      'password_hash' => 'aa2gsdg123hfgukfyrtweri',
      'email' => 'some@email',
      'status' => 10,
    ];
    return new static($arr);
}

I too tried alternative variat method like:

public static function findByRoot()
  {
    $model = new User();
    $model->id = '1000';
    $model->username = 'vasya';
    $model->status = 10;
    return $model;
  }

Yii::$app->getUser()->login() requires implements from UserIdentity

Do auth:

\Yii::$app->getUser()->login(User::findByRoot());

If I put real name from db in login method it returned TRUE and that's OK

But if put User::findByRoot() (the same object) it returned too TRUE but Yii::$app->user->identity has NULL

What's problem?

Yii::$app->user->identity returns null in case it can't find user's id. To fix that, first of all make sure, you supply the right id here:

public static function findIdentity($id)
{
    // dump $id here somehow, does it belong to the static collection?
    return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}

Second option you have, is to always return the instance with filled data, since you use a fake data to test it anyway.

public static function findIdentity($id)
{
    // just ignore the $id param here
    return new static(array(
        'updated_at' => '...',
        'username' => '....',
        // and the rest 
    ));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM