Skip to content

Instantly share code, notes, and snippets.

@erycamel
Last active February 8, 2019 08:44
Show Gist options
  • Save erycamel/994c889b1e1840cd7bc3 to your computer and use it in GitHub Desktop.
Save erycamel/994c889b1e1840cd7bc3 to your computer and use it in GitHub Desktop.
Yii2 Authenticating by Email Address
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;
}
------------------------------------------
@erycamel
Copy link
Author

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' => ['@'],
],
],
],

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment