Roberto
Roberto

Reputation: 1087

CakePHP 3.x - Modify user data in Auth component before session creation

When using the Auth component in CakePHP 3 you can define the findAuth() finder (or configure a different finder) to have control over what data is loaded:

// AppController
$this->loadComponent('Auth', [
    //...
    'authenticate' => [
        'Form' => [
            'finder' => 'auth'
        ]
    ],
    //...
]);


// UsersTable
public function findAuth($query, array $options)
{
    return $query
        ->...;
}

I need some functionality that cannot be done with the query builder. How can I post-process the loaded auth data before session creation?
Note that I have different ways of logging in my users, so I would prefer this be kept inside the AuthComponent logic.

(This is still for CakePHP 3, but a brief comment on how this could be done in the new CakePHP 4 Authentication plugion would also be appriciated.)

EDIT: Rough outline of what I need: data needs to re-organised in the users array based on current context, i.e. users can have an active project selected.

Upvotes: 0

Views: 133

Answers (1)

ndm
ndm

Reputation: 60453

I'm still not really sure what exactly you need to re-organize in what way exactly, but generally you can modify the queried data using mappers/reducers and result formatters, the latter usually being the easier way.

Here's a quick example that would add an additional field named additional_data to the result in case a field named active_project_id is set:

$query->formatResults(function (\Cake\Collection\CollectionInterface $results) {
    return $results->map(function ($row) {
        if (isset($row['active_project_id'])) {
            $row['additional_data'] = 'lorem ipsum';
        }

        return $row;
    });
});

Such a finder query would work with the new authentication plugin too.

See also

Upvotes: 1

Related Questions