I have a second DB where I store users and a few more things. The connection works fine, I can retrieve all the users using the User model.
I also use that model for authentication. I did it this way on a few projects and the code works without trouble.
This is my config:
config/web.php
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
'identityCookie' => [
'name' => '_frontendUser', // i've added this to check if the cookie is being created and yes, it is
]
],
app\models\User:
class User extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface {
[..]
public $authKey = 'my auth key here';
public static function getDb()
{
return \Yii::$app->get('db2');
}
public static function tableName()
{
return 'users';
}
public static function findIdentity($id) {
$dbUser = self::find()
->where([
"id_user" => $id
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
public static function findIdentityByAccessToken($token, $type = null)
{
return static::findOne(['access_token' => $token]);
}
public static function findByEmail($email)
{
$dbUser = User::find()
->where([
"e_mail" => $email
])
->one();
if (!count($dbUser)) {
return null;
}
return new static($dbUser);
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
public function validatePassword($password)
{
return $this->password === hash('sha512', $password.$this->authKey);
}
SiteController:
public function actionLogin()
{
$this->layout = 'frontend';
if (!\Yii::$app->user->isGuest) {
return $this->goHome();
}
$model = new LoginForm;
if ($model->load(Yii::$app->request->post()) && $model->login()) {
//\yii\helpers\VarDumper::dump($model->login(), 10, true); //this VarDumper returns true which means $model->login() is working but it redirects me to site/login
return $this->goBack();
} else {
return $this->render('login', [
'model' => $model,
]);
}
}
Any idea on what’s wrong?