Accessing auth identity inside a Table class

I have a versions table that hasMany version_log. When a version is edited, I’d like to log the change automatically and save the user_id of the person who made the change.

To start, I’ve built a beforeSave method in Model/Table/VersionsTable, but I can’t figure out how to get the ID of the logged in user from the Auth session.

  public function beforeSave($event, $entity, $options)
    {
        if ($entity->isDirty('status')) {
            $versionLog = $this->VersionLog->newEmptyEntity();
            $versionLog->version_id = $entity->get('id');
            $versionLog->old_status = $entity->getOriginal('status');
            $versionLog->new_status = $entity->get('status');
            $versionLog->user_id = $this->Authentication->getIdentity()->getIdentifier(); // Does not work
            $this->VersionLog->save($versionLog);
         }

    }

Somewhat related… I originally tried to save the associated VersionLog data automatically, by creating an array and then associating it with the parent Version entity, with something like the following

$entity->version_log[] = $versionLog;

But I couldn’t get the associated data to save at all. So I’m probably going about this incorrectly.

To get access to the logged in user in the model you can use GitHub - UseMuffin/Footprint: CakePHP plugin to allow passing currently logged in user to model layer.

1 Like

Hello seagrinch.
Note that when using the authentication component in CakePHP4, as in my case, the user data is stored in session variables, which allows access to them from any controller in the code.

I do it like that:

> $session = $this->request->getSession();
> $userID= $session->read('Auth.id');
> $group = $session->read('Auth.group');

Sintaxis:

$session = $this->request->getSession();
$var = $session->read(‘Auth.FieldName’);

This way you can capture the data you need and assign it to the fields of your logs table.

More info about sessions in: Accessing the Session Object in CakePHP 4

I hope this info helps you.

Thanks @mellileo. Unfortunately, I’m trying to do this from within the Model’s beforeSave(), and I don’t think Request is available there. Indeed, the doc only says Controllers and Views (and their related sub-features).

Thanks @KevinPfeifer. That seems to be a nice solution. I’m always reluctant to include a plugin for one task, but it seems simple enough and I like how you can use it to add automatic created_by and update_by fields too.