T
T
teodor7teodor72016-04-05 15:10:49
Yii
teodor7teodor7, 2016-04-05 15:10:49

Yii2 how to make authentication from standard?

Good afternoon. Tell me how to do authentication, I read the documentation, I watch the video, but I don’t understand a little. You need to change the standard set so that it connects to the database, and by name and password it transfers to another page. Here we have a controller with a method

.....
 public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->render('login');
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->redirect(['users/index']);
        }
        return $this->render('login', [
            'model' => $model,
        ]);
    }

....

That is, there is a redirect to another page.
Faced a problem. I don’t understand how to connect with the database
, here is the standard model LoginForm included the database there
... public static function tableName()
    {
        return 'users';
    }...

Then I check in the same model and login ...
public function login()
    {



        return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);

    }public function getUser()
    {
        if ($this->_user === false) {$identity = User::findOne($this->username);

        }

        return $this->_user;
    }

How to do it?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2016-04-05
@teodor7teodor7

You are probably looking for this:

public function login()
    {
        if (!$this->validate()) {
            return false;
        }

        $attributes = [
            'email' => $this->username,
            'active' => true
        ];

        /* @var User $user */
        if (($user = User::findOne($attributes)) && User::validatePassword($user, $this->password)) {
            return \Yii::$app->user->login($user, $this->rememberMe ? self::$timeout : 0);
        }

        $this->addError('username', \Yii::t('models/LoginForm', 'Wrong E-Mail or password'));

        return false;
    }

G
glamurchik, 2016-04-05
@glamurchik

Why do it if it works anyway?
you need to connect the database settings
and do yii/migrate

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question