MultiAuth Login via Custom Finder in Cake3 - How?

The goal is to give users the ability to login with multiple fields, such as email or username.

I’ve heard that this can be achieved with Custom Finder Methods in CakePHP 3. But I can’t figure out how this is supposed to work…

Has anyone achieved this or knows another way? The plugins I originally intended to use for it say Custom Finders are the way to go, but I could find no further info on that topic.

1 Like

Wait for this PR to be merged https://github.com/cakephp/cakephp/pull/8704

2 Likes

The PR mentioned above has been merged and will be available in 3.2.9 release. You can use the master branch if you need it right away :slight_smile:

Thanks for the info ADmad!

For everyone else to whom it’s not entirely clear how to implement this feature, here’s a quick how-to:

  1. Make sure you have CakePHP 3.2.9 installed.

  2. To the configuration of the Auth component, add:

    ‘authenticate’ => [
    ‘Form’ => [
    ‘finder’ => ‘auth’
    ]
    ]

  3. Then to your UsersTable add:

    public function findAuth(\Cake\ORM\Query $query, array $options)
    {
    $query
    ->select([‘id’, ‘username’, ‘email’, ‘password’]) //Or whichever fields you need
    ->where([‘Users.username’ => $options[‘username’]])
    ->orWhere([‘Users.email’ => $options[‘username’]])
    ->andWhere([‘Users.active’ => 1]); //If applicable in your case…

     	return $query;
     }
    

$options[‘username’] contains whatever was typed into the form, whether an email or the username.

Hopefully this will be of some use, since the way it works is not immediately obvious.

1 Like