Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CakePHP 3 - Multiple field Auth login

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?

like image 487
Sumon Sarker Avatar asked Jan 03 '23 08:01

Sumon Sarker


1 Answers

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

  • Cookbook > Controllers > Components > Authentication > Configuring Authentication Handlers
  • Cookbook > Controllers > Components > Authentication > Customizing Find Query
like image 79
ndm Avatar answered Jan 08 '23 07:01

ndm