CakePHP 3 - Auth Multi-User Login

I want to log in using multiple field validation.

Current Situation: Using ( Email ) and ( Password ) Login Fields

 <div> <input name="email" placeholder="Email"> <input name="password" placeholder="Password"> <input type="submit" value="Login"> </div> 

Here are my AuthComponent configurations:

 $this->loadComponent('Auth', [ #Some other configuration 'authenticate' => [ 'Form' => [ 'fields' => ['username' => 'email'] ] ], 'storage' => 'Session' ]); 

My expectation: using ( Email or Phone ) and ( Password ) login fields

 <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?

+5
source share
2 answers

If you want to perform authentication based on "either" or "basis", you need to use a custom search, since the built-in authenticator search is designed to match only one column.

In your form, define the input:

 <?= $this->Form->input('email_or_phone'); ?> 

In your auth configuration, configure the fields and finder:

 $this->loadComponent('Auth', [ 'authenticate' => [ 'Form' => [ 'fields' => [ 'username' => 'email_or_phone' ], 'finder' => 'auth' ] ] ]); 

In your (possibly UsersTable ) table class, define finder, where you can use the username parameter to build the necessary 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 ); } 

Please note that the value that the authenticator captures from the request through the configured email_or_phone field will always be passed to the finder in the username option!

Also note that you must either remove the possible existing conditions generated by the authenticator or overwrite them as shown in this example using the third argument to Query::where() .

see also

+4
source

Try the following:

 $this->loadComponent('Auth', [ #Some other configuration 'authenticate' => [ 'Form' => [ 'fields' => ['username' => ['email','phone']] ] ], 'storage' => 'Session' ]); 

Just pass the values โ€‹โ€‹as an array to username .

And in your login function, do something like:

 $username = $this->data['User']['username']; $user = $this->User->findByEmail($username); if (empty($user)) { $user = $this->User->findByPhone($username); } 
+2
source

Source: https://habr.com/ru/post/1272553/


All Articles