Last active
February 8, 2019 08:44
-
-
Save erycamel/994c889b1e1840cd7bc3 to your computer and use it in GitHub Desktop.
Yii2 Authenticating by Email Address
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Yii2 Authenticating by Email Address | |
how to authenticate to either a username or email entered into the Login form. | |
modify two things. | |
1. First modify the User model (found in /common/models/ for advanced template or /models in the basic template) | |
to have a new function as below: | |
--------------------------------------- | |
/** | |
* Finds user by email | |
* | |
* @param string $email | |
* @return static|null | |
*/ | |
public static function findByEmail($email) | |
{ | |
return static::findOne(['email' => $email, 'status' => self::STATUS_ACTIVE]); | |
} | |
-------------------------------------------- | |
2. Second modify the LoginForm (found in /common/models/ for advanced template or /models in the basic template). | |
Locate the getUser function and modify it as below: | |
--------------------------------------------- | |
/** | |
* Finds user by [[username]] | |
* | |
* @return User|null | |
*/ | |
public function getUser() | |
{ | |
if ($this->_user === false) { | |
$this->_user = User::findByUsername($this->username); | |
if(!$this->_user) | |
$this->_user = User::findByEmail($this->username); | |
} | |
return $this->_user; | |
} | |
------------------------------------------ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yii2 global filter/behavior to force user to authenticate first
add the following code below 'components' => [...]
'as beforeRequest' => [
'class' => 'yii\filters\AccessControl',
'rules' => [
[
'actions' => ['login', 'error'],
'allow' => true,
],
[
'allow' => true,
'roles' => ['@'],
],
],
],