M
M
Mors Clamor2019-09-15 22:42:10
Yii
Mors Clamor, 2019-09-15 22:42:10

How to authenticate a user in Yii2?

Hello. I'm trying to switch from microframeworks to full-fledged ones, namely Yii2 or Laravel, but from my point of view, they are both almost equally incomprehensible. Yii2 already has basic tables with basic fields for registration and authorization and so on. I want to use my fields and my authentication logic. For starters, at least the fields. Everything according to the instructions.
My controller:

namespace app\controllers;

use Yii;
use yii\web\Controller;
use app\models\User;

class TestController extends Controller
{

  public function actionRegister() {
    $user=User::findOne(["id"=>1]);
    Yii:$app->user->login($user);
    if(Yii::$app->user->isGuest) {
        return "Вы гость";
    }
  }
}

And the actual model User (ActiveRecord) that implements the interface:
namespace app\models;

use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
  public static function tableName()
  {
      return 'users';
  }

    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
    //    return 1;
    }

    public function getId()
    {
        return $this->id;
    }

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

    public function validateAuthKey($authKey)
    {
        //return $this->authKey === $authKey;
    }
}

The problem is, on the line with
Yii:$app->user->login($user);
in the controller, Yii gives "Call to a member function login() on null". As I understand it, it does not pull out the user.
5d7e93eec3584153721648.png
What am I doing wrong?
Added: I'm hysterical, the literally copied code from the advanced template and corrected for my table does not work. It authorizes, but all fields of the user object are null. Maybe I'm creating the database somehow wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2019-09-15
@66demon666

Try this: In general, download the advanced template and see how it is implemented there. You can copy to yourself and not invent.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question