I want to login using multiple field checking.
Current situation : Using (Email
) And (Password
) fields for login
<div>
<input name="email" placeholder="Email">
<input name="password" placeholder="Password">
<input type="submit" value="Login">
</div>
Here is my AuthComponent configurations :
$this->loadComponent('Auth', [
#Some other configuration
'authenticate' => [
'Form' => [
'fields' => ['username' => 'email']
]
],
'storage' => 'Session'
]);
My expectation : Using (Email
Or Phone
) And (Password
) fields for login
<div>
<input name="email_or_phone" placeholder="Email or Phone">
<input name="password" placeholder="Password">
<input type="submit" value="Login">
</div>
How can I configure AuthComponent to meet this situation?
If you want to authenticate based on an "either or" basis, then you have to use a custom finder, as the built-in finder of the authenticator is designed to match against a single column only.
In your form define the input:
<?= $this->Form->input('email_or_phone'); ?>
In your auth configuration set up the fields and finder:
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'fields' => [
'username' => 'email_or_phone'
],
'finder' => 'auth'
]
]
]);
In your (probably UsersTable
) table class define the finder, where you can use the username
option to build the required conditions:
public function findAuth(\Cake\ORM\Query $query, array $options)
{
return $query->where(
[
'OR' => [
$this->aliasField('email') => $options['username'],
$this->aliasField('phone') => $options['username'],
]
],
[],
true
);
}
Note that the value that the authenticator grabs from the request via the configured email_or_phone
field, will always be passed to the finder in the username
option!
Also note that you have to either remove possible existing conditions generated by the authenticator, or overwrite them as show in this example, using the third argument of Query::where()
.
See also
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With