I want to allow user login from two different models.
config.php
'user' => [ 'identityClass' => 'app\models\User',
LoginForm.php
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'], ]; } public function validatePassword($attribute, $params) { if (!$this->hasErrors()) { $user = $this->getUser(); if (!$user || !$user->validatePassword($this->password)) { $this->addError($attribute, Yii::t('user', 'Incorrect username or password.')); } } } public function login() { if ($this->validate()) { return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); } else { return false; } } public function parentLogin() { // How to validate parent Login? } public function getUser() { if ($this->_user === false) { $this->_user = User::findByUsername($this->username); } return $this->_user; }
User.php
class User extends \yii\db\ActiveRecord implements IdentityInterface { public static function tableName() { return 'users'; } public static function findIdentity($id) { return static::findOne($id); } public static function findByUsername($username) { return static::findOne(['user_login_id' => $username]); }
controller.php
public function actionLogin() { // Working } public function actionParentLogin() { $model = new LoginForm(); if ($model->load(Yii::$app->request->post()) && $model->parentLogin()) { $parent = ParentLogin::find()->where(['p_username' => $model->p_username])->one(); if($parent){ \Yii::$app->session->set('p_id',$parent->p_id); return $this->redirect(['parent-dashboard']); } else { Yii::$app->getSession()->setFlash('error', Yii::t('site', 'Incorrect username or password.')); } } return $this->render('parent-login', [ 'model' => $model, ]); }
I do not know how to check the registration of the parent. For many hours I tried to find a workaround, but could not.
I am stuck on Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); because there are no parent login entries in the user table.
My questions
1) Is it possible to have two identityClass . If so, how?
2) Is it possible to extend the ParentLogin model to User . If so, how to check?
References
How to extend a user class? Configuring the CWebUser Class
User class userIdentity in yii2