I want to allow user login from two different model.
Config.php
'user' => [
'identityClass' => 'app\models\User', //one more class here
'enableAutoLogin' => false,
'authTimeout' => 3600*2,
],
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 don't know how to validate parent login. I tried for hours finding workaround but not succeed.
I am stuck on Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0); because user table don't have parent login records.
My questions
1) Is it possible to have two identityClass. If yes then how?
2) Is it possible to extend ParentLogin model to User. If yes then how to validate?
References
How To extend user class?
Customising the CWebUser class
Custom userIdentity class in yii2